-
Notifications
You must be signed in to change notification settings - Fork 9
/
二叉树_创建_递归遍历___.cpp
88 lines (81 loc) · 1.16 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
#include<stdio.h>
#include<stdlib.h>
#define MAX 50
typedef struct TreeNode
{
char data;
struct TreeNode *lchild,*rchild;
}TreeNode;
int createTree(TreeNode *&T)
{
char ch;
scanf("%c",&ch);
printf("-->%c",ch);
if(ch==' ')
{
T=NULL;
}
else
{
T=(TreeNode*)malloc(sizeof(TreeNode));
if(!T)
{
exit(-1);
}
T->data=ch;
createTree(T->lchild);
createTree(T->rchild);
}
return 0;
}
int visit(TreeNode *&T)
{
printf("%c",T->data);
}
int firstPrint(TreeNode *&T)
{
if(T)
{
visit(T);
firstPrint(T->lchild);
firstPrint(T->rchild);
}
}
int centerPrint(TreeNode *&T)
{
if(T)
{
centerPrint(T->lchild);
visit(T);
centerPrint(T->rchild);
}
}
int behindPrint(TreeNode *&T)
{
if(T)
{
behindPrint(T->lchild);
behindPrint(T->rchild);
visit(T);
}
}
int main()
{
TreeNode *T;
printf("请先序输入二叉树,' '代表NULL:\n");//12 6 43 7 ;
createTree(T);
printf("\n先序遍历:\n");
firstPrint(T);
printf("\n中序序遍历:\n");
centerPrint(T);
printf("\n后序遍历:\n");
behindPrint(T);
/*
1
/ \
2 4
\ / \
6 3 7
*/
return 0;
}