-
Notifications
You must be signed in to change notification settings - Fork 430
/
BST.c
152 lines (136 loc) · 2.94 KB
/
BST.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
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
//二叉查找树的创建
template<typename T>
void BSTree<T>::createBSTreeByFile(ifstream &f){
T e;
queue<BSNode<T>*> q;
while(!f.eof()){
InputFromFile(f, e);
Insert(root, e);
}
}
template<typename T>
void BSTree<T>::Insert(BSNode<T>* &t, T x){//得用指针的引用,不然传参时由于形参实例化,并不能成功创建二叉树
if(t==NULL){
t = new BSNode<T>;
t->data = x;
t->lchild = t->rchild = NULL;
return;
}
if(x<=t->data){
Insert(t->lchild, x);
}
else{
Insert(t->rchild, x);
}
}
//前序遍历
template<typename T>
void BSTree<T>::PreOrderTraverse(void(*visit)(BSNode<T>&))const{
stack<BSNode<T>*> s;
BSNode<T> *t = root;
while(NULL!=t || !s.empty()){
if(NULL!=t){
s.push(t);
visit(*t);
t = t->lchild;
}
else{
t = s.top();
s.pop();
t = t->rchild;
}
}
cout<<endl;
}
//中序遍历
template<typename T>
void BSTree<T>::InOrderTraverse(void(*visit)(BSNode<T>&))const{
stack<BSNode<T>*> s;
BSNode<T> *q;
q = root;
while(!s.empty()||q!=NULL){
if(q!=NULL){
s.push(q);
q = q->lchild;
}
else{
q = s.top();
s.pop();
visit(*q);
q = q->rchild;
}
}
cout<<endl;
}
//后序遍历
/*结构体部分*/
enum Tags{Left, Right};
template<typename T>struct StackElem
{
BSNode<T> *p;
Tags flag;
};
/*后序遍历代码部分*/
template<typename T>
void BSTree<T>::PostOrderTraverse(void(*visit)(BSNode<T>&))const{
StackElem<T> se;
stack<StackElem<T> > s;
BSNode<T> *t;
t = root;
if(t==NULL){
return;
}
while(t!=NULL||!s.empty()){
while(t!=NULL){
se.flag = Left;
se.p = t;
s.push(se);
t = t->lchild;
}
se = s.top();
s.pop();
t = se.p;
if(se.flag==Left){
se.flag = Right;
s.push(se);
t = t->rchild;
}
else{
visit(*t);
t = NULL;
}
}
}
//递归前序遍历
template<typename T>
void BSTree<T>::PreTraverse(BSNode<T> *t, void(*visit)(BSNode<T>&))const{
if(t==NULL){
return;
}
else{
visit(*t);
PreTraverse(t->lchild, visit);
PreTraverse(t->rchild, visit);
}
}
//递归中序遍历
template<typename T>
void BSTree<T>::InTraverse(BSNode<T> *t, void(*visit)(BSNode<T>&))const{
if(t==NULL){
return;
}
else{
InTraverse(t->lchild, visit);
visit(*t);
InTraverse(t->rchild, visit);
}
}
//递归后序遍历
template<typename T>
void BSTree<T>::PostTraverse(BSNode<T> *t, void(*visit)(BSNode<T>&))const{
if(t!=NULL){
PostTraverse(t->lchild, visit);
PostTraverse(t->rchild, visit);
visit(*t);
}
}