forked from Vencenter/C_Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path二叉树_线索二叉树_.cpp
126 lines (112 loc) · 1.84 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define STACK_INIT_SIZE 100
#define addsize 60
typedef int Status;
typedef char elemment;
//枚举,Link为0,Thread为1
typedef enum
{
Link,
Thread
}Tag;
typedef struct BitNode
{
elemment data;
struct BitNode *lchild ,*rchild;
int ltag,rtag;
}BitNode, *BitTree;
BitTree pre=NULL;
//中序对二叉树进行线索化
void CreateBtree(BitTree &T )
{
//创建二叉树
char ch;
scanf("%c",&ch);
//printf("-->%c\n",ch);
if(ch==' ')
{
T=NULL;
}
else
{
if(!(T=(BitNode * )malloc(sizeof(BitNode))))
{
exit(OVERFLOW);
}
T->ltag = T->rtag = Link;
T->data=ch;
CreateBtree(T->lchild);
CreateBtree(T->rchild);
}
}
print(BitTree T)
{
if(T)
{
printf("%c\n",T->data);
print(T->lchild);
print(T->rchild);
}
}
//中序对二叉树进行线索化
int InThreading(BitTree &T)
{
if(T)
{
InThreading(T->lchild);
if(!T->lchild)
{
T->lchild=pre;
T->ltag=Thread;
}
if(pre&&!pre->rchild)
{
pre->rchild=T;
pre->rtag=Thread;
}
pre=T;
InThreading(T->rchild);//递归右子树进行线索化
}
return 0;
}
int InOrderThraverse_Thr(BitTree T)
{
while(T)
{
while(T->ltag == Link)
{
T = T->lchild;
}
printf("%c\n", T->data); //操作结点数据
while(T->rtag==Thread && T->rchild!=NULL)
{
T=T->rchild;
printf("%c\n", T->data); //操作结点数据
}
T=T->rchild;
}
return 0;
}
int main()
{
BitTree T;
CreateBtree(T);
printf("输出中序序列:\n");
print(T);
InThreading(T);
printf("输出中序线索序列:\n");
InOrderThraverse_Thr(T);
// 采用先序输入,例如124 5 36 7 ;
/*
1
/ \
2 4
\ / \
6 3 7
*/
return 0;
}