forked from Vencenter/C_Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
二叉树_创建_递归遍历_(数组)_.cpp
100 lines (82 loc) · 1.42 KB
/
二叉树_创建_递归遍历_(数组)_.cpp
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
#include<stdio.h>
#include<stdlib.h>
#define MAX 256
typedef char TElemType;
typedef struct BiTNode
{
TElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*Bitree;
Bitree CreateBitree(char nodes[],int n)
{
BiTNode *r;
if (nodes[n]=='#')
{
return NULL;
}
r=(BiTNode *)malloc(sizeof(BiTNode));
r->data=nodes[n];
r->lchild=CreateBitree(nodes,2*n);
r->rchild=CreateBitree(nodes,2*n+1);
return r;
}
void Prefirst(Bitree r)
{
if(r!=NULL)
{
printf("%c",r->data);
Prefirst(r->lchild);
Prefirst(r->rchild);
}
}
void Precenter(Bitree r)
{
if(r!=NULL)
{
Precenter(r->lchild);
printf("%c",r->data);
Precenter(r->rchild);
}
}
void Prebehind(Bitree r)
{
if(r!=NULL)
{
Prebehind(r->lchild);
Prebehind(r->rchild);
printf("%c",r->data);
}
}
int main()
{
int i;
char c;
char nodes[MAX];
Bitree r;
for(i=0;i<MAX;i++)
{
nodes[i]='#';
}
printf("input顺序表的结构,\n结束 :\n");
for(i=1;i<MAX;i++)
{
c=getchar();
if(c=='\n')
{
break;
}
nodes[i]=c;
}
r=CreateBitree(nodes,1);
printf("顺序表的结构,成功 !\n");
printf("二叉树,先序遍历结果: \n");
Prefirst(r) ;
printf("\n");
printf("二叉树,中序遍历结果:\n");
Precenter(r) ;
printf("\n");
printf("二叉树,后序遍历结果:\n");
Prebehind(r) ;
printf("\n");
return 0;
}