数据结构系列12 - 二叉树的层次遍历 - C语言实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*************************************************************************
* File Name: treeLevelTraverse.c
* Author: TyrantLucifer
* E-mail: TyrantLucifer@gmail.com
* Blog: https://tyrantlucifer.com
* Created Time: Thu 13 May 2021 07:03:14 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>

typedef struct TreeNode {
char data;
struct TreeNode* lchild;
struct TreeNode* rchild;
}TreeNode;

typedef struct QueueNode {
TreeNode* data;
struct QueueNode* pre;
struct QueueNode* next;
}QueueNode;

void createTree(TreeNode** T, char* data, int* index) {
char ch;
ch = data[*index];
*index += 1;
if (ch == '#') {
*T = NULL;
}
else {
*T = (TreeNode*)malloc(sizeof(TreeNode));
(*T) -> data = ch;
createTree(&((*T)->lchild), data, index);
createTree(&((*T)->rchild), data, index);
}
}

void preOrder(TreeNode* T) {
if (T == NULL) {
return;
}
else {
printf("%c ", T->data);
preOrder(T->lchild);
preOrder(T->rchild);
}
}

QueueNode* initQueue() {
QueueNode* Q = (QueueNode*)malloc(sizeof(QueueNode));
Q->data = NULL;
Q->next = Q;
Q->pre = Q;
return Q;
}

void enQueue(TreeNode* data, QueueNode* Q) {
QueueNode* node = (QueueNode*)malloc(sizeof(QueueNode));
node->data = data;
node->pre = Q;
node->next = Q;
Q->pre->next = node;
Q->pre = node;
}

int isEmpty(QueueNode* Q) {
if (Q->next == Q) {
return 1;
}
else {
return 0;
}
}

QueueNode* deQueue(QueueNode* Q) {
if (isEmpty(Q)) {
return NULL;
}
else {
QueueNode* node = Q->next;
Q->next->next->pre = Q;
Q->next = Q->next->next;
return node;
}
}

void levelTraverse(QueueNode* Q, TreeNode* T) {
enQueue(T, Q);
while (!isEmpty(Q)) {
QueueNode* node = deQueue(Q);
printf("%c ", node->data->data);
if (node->data->lchild) {
enQueue(node->data->lchild, Q);
}
if (node->data->rchild) {
enQueue(node->data->rchild, Q);
}
}
}

int main (int argc, char* argv[]) {
TreeNode* T;
int index = 0;
QueueNode* Q = initQueue();
createTree(&T, argv[1], &index);
preOrder(T);
printf("\n");
levelTraverse(Q, T);
printf("\n");
return 0;
}