用先序递归过程建立二叉树 (存储结构:二叉链表) 输入数据按先序遍历所得序列输入,当某结点左子树或右子树为空时,输入‘*’
号,如输入abc**d**e**
得到的二叉树如下: 1
2
3 a
b e
c d1
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#include <cstdio>
#include <cstdlib>
#include <cstring>
typedef struct tree{//二叉树结构
char data;
struct tree *lc,*rc;
}BitNode,*BitTree;
typedef struct queu{//先序序列存储队列,包含'*'
char data;
struct queu *next;
}QueueNode,*Queue;
Queue head = NULL,rear = head;
void enqueue(Queue &head, Queue &rear,char ch){//入队
Queue p = (Queue)malloc(sizeof(QueueNode));
p->data = ch;
p->next = NULL;
if(head == NULL){
head = p;
rear = p;
}
else{
rear->next = p;
rear = p;
}
return ;
}
Queue Del(Queue head){//删除节点操作
Queue temp = head -> next;
free(head);
return temp;
}
char dequeue(Queue &head){//出队
if(head == NULL)
return NULL;
char ch = head->data;
head = Del(head);
return ch;
}
void BuildTree(BitTree &root){//根据带'*'先序序列建树
char ch = dequeue(head);
if(ch == '*' || ch == '\0')//遇到'*',直接返回
return;
root = (BitTree)malloc(sizeof(BitNode));
root->data = ch;
root->lc = NULL;
root->rc = NULL;
BuildTree(root->lc);
BuildTree(root->rc);
return ;
}
void PreOrder(BitTree root){//先序遍历输出
printf("%c",root->data);
if(root->lc)
PreOrder(root->lc);
if(root->rc)
PreOrder(root->rc);
}
void MidOrder(BitTree root){//中序遍历输出
if(root->lc)
PreOrder(root->lc);
printf("%c",root->data);
if(root->rc)
PreOrder(root->rc);
}
void AftOrder(BitTree root){//后续遍历输出
if(root->lc)
AftOrder(root->lc);
if(root->rc)
AftOrder(root->rc);
printf("%c",root->data);
}
int main(){
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
char ch[10000];
scanf("%s",ch);
for(int i = 0;ch[i] != '\0';i++)
enqueue(head,rear,ch[i]);
BitTree root;
BuildTree(root);
PreOrder(root);
printf("\n");
MidOrder(root);
printf("\n");
AftOrder(root);
printf("\n");
return 0;
}
用先序递归过程建立二叉树
最后更新时间:
欢迎评论~