代码地址:http://www.oschina.net/code/snippet_166683_5323
1. [代码][C/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
|
//按先序扩展序列建立二叉树. 三种递归遍历按先序扩展序列建立二叉树. 三种递归遍历
#include <iostream>
#include <stdlib.h>
#include <malloc.h>
#include <stdio.h>
typedef
struct
node
{
char
data;
struct
node *lchild;
struct
node *rchild;
}*BiTree;
void
creatBT(BiTree &T)
//建立一个二叉树的函数
{
char
ch;
scanf
(
"%c"
,&ch);
if
(ch==
'.'
)
{
T=NULL;
// . 代表空子树;
}
else
{
T=(node *)
malloc
(
sizeof
(node));
//分配一个node的空间
if
(!T)
exit
(0);
T->data = ch;
//给T赋值
creatBT(T->lchild);
//给左子树赋值
creatBT(T->rchild);
//给右子树赋值
}
}
void
pre_order(node *T)
//前序遍历二叉树
{
if
(T)
{
printf
(
"%c "
,T->data);
pre_order(T->lchild);
pre_order(T->rchild);
}
}
void
mid_order(node *T)
//中序遍历二叉树
{
if
(T)
{
mid_order(T->lchild);
printf
(
"%c "
,T->data);
mid_order(T->rchild);
}
}
void
behind_order(node *T)
//后序遍历二叉树
{
if
(T)
{
behind_order(T->lchild);
behind_order(T->rchild);
printf
(
"%c "
,T->data);
}
}
int
main()
{
node *T;
printf
(
"请输按先序序列输入一串字符,当子树为空时,用.来代替\n"
);
creatBT(T);
//建树
printf
(
"建树成功,T指向二叉树的根!\n"
);
printf
(
"\n前序遍历二叉树的结果是:"
);
pre_order(T);
printf
(
"\n中序遍历二叉树的结果是:"
);
mid_order(T);
printf
(
"\n后序遍历二叉树的结果是:"
);
behind_order(T);
printf
(
"\n"
);
system
(
"pause"
);
return
0;
}
|
2. [代码][C/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
|
//按先序扩展序列建立二叉树. 三种递归遍历按先序扩展序列建立二叉树. 三种递归遍历
#include <iostream>
#include <stdlib.h>
#include <malloc.h>
#include <stdio.h>
typedef
struct
node
{
char
data;
struct
node *lchild;
struct
node *rchild;
}*BiTree;
void
creatBT(BiTree &T)
//建立一个二叉树的函数
{
char
ch;
scanf
(
"%c"
,&ch);
if
(ch==
'.'
)
{
T=NULL;
// . 代表空子树;
}
else
{
T=(node *)
malloc
(
sizeof
(node));
//分配一个node的空间
if
(!T)
exit
(0);
T->data = ch;
//给T赋值
creatBT(T->lchild);
//给左子树赋值
creatBT(T->rchild);
//给右子树赋值
}
}
void
pre_order(node *T)
//前序遍历二叉树
{
if
(T)
{
printf
(
"%c "
,T->data);
pre_order(T->lchild);
pre_order(T->rchild);
}
}
void
mid_order(node *T)
//中序遍历二叉树
{
if
(T)
{
mid_order(T->lchild);
printf
(
"%c "
,T->data);
mid_order(T->rchild);
}
}
void
behind_order(node *T)
//后序遍历二叉树
{
if
(T)
{
behind_order(T->lchild);
behind_order(T->rchild);
printf
(
"%c "
,T->data);
}
}
int
main()
{
node *T;
printf
(
"请输按先序序列输入一串字符,当子树为空时,用.来代替\n"
);
creatBT(T);
//建树
printf
(
"建树成功,T指向二叉树的根!\n"
);
printf
(
"\n前序遍历二叉树的结果是:"
);
pre_order(T);
printf
(
"\n中序遍历二叉树的结果是:"
);
mid_order(T);
printf
(
"\n后序遍历二叉树的结果是:"
);
behind_order(T);
printf
(
"\n"
);
system
(
"pause"
);
return
0;
}
|