-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary_Delete.cpp
165 lines (144 loc) · 3.32 KB
/
Binary_Delete.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
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
153
154
155
156
157
158
159
160
161
162
163
164
165
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
template<class K>
struct BSTreeNode{
BSTreeNode* lchild;
BSTreeNode* rchild;
K key;
BSTreeNode(const K& key_){
lchild=NULL;
rchild=NULL;
key=key_;
}
};
template<class K>
class BSTree{
private:
typedef BSTreeNode<K> Node;
Node *root;
public:
//构造函数
BSTree():root(NULL){}
//非递归插入节点
bool Insert(const K& key_){
//如果是根节点 直接初始化
if (root==NULL){
root=new Node(key_);
}
Node* cur=root;
Node* parent=NULL;
while (cur){
if (cur->key > key_){
parent=cur;
cur=cur->lchild;
}
else if (cur->key<key_){
parent=cur;
cur=cur->rchild;
}
else{
//树中已经存在该值
return false;
}
}
if (parent->key>key_){
parent->lchild=new Node(key_);
}
else{
parent->rchild=new Node(key_);
}
return true;
}
//递归插入节点
bool Insert_R(const K& key_){
_Insert_R(root,key_);
}
//前序遍历
void Pre_Order(){
_Pre_Order(root);
cout<<endl;
}
//中序遍历
void In_Order(){
_In_Order(root);
cout<<endl;
}
Node* Find(const K&key_){
Node* cur=root;
while (cur){
if (cur->key>key_){
cur=cur->lchild;
}
else if (cur->key<key_){
cur=cur->rchild;
}
else return cur;
}
return NULL;
}
//递归查找
Node * Find_R(const K&key_){
return _Find_R(root,key_);
}
bool Remove(const K&key_){
//如果根节点为空 失败
if (root==NULL) return false;
if (root->lchild==NULL&&root->rchild==NULL){
}
}
protected:
//前序遍历
void _Pre_Order(Node *T){
if (T!=NULL){
cout<<T->key<<" ";
_Pre_Order(T->lchild);
_Pre_Order(T->rchild);
}
}
void _In_Order(Node *T){
if (T!=NULL){
_In_Order(T->lchild);
cout<<T->key<<" ";
_In_Order(T->rchild);
}
}
bool _Insert_R(Node *& T,const K& key_){
if (T==NULL){
T=new Node(key_);
}
if (T->key>key_){
return _Insert_R(T->lchild,key_);
}
else if (T->key<key_){
return _Insert_R(T->rchild,key_);
}
else return false;
}
Node * _Find_R(Node *T,const K&key_){
if (T==NULL) return NULL;
if (T->key==key_) return T;
else if (T->key>key_) {
return _Find_R(T->lchild,key_);
}
else if (T->key<key_){
return _Find_R(T->rchild,key_);
}
}
};
int main(){
int A[]={4,2,3,9,6,5,10,1,7};
BSTree<int> bstree;
for (int i=0;i<9;i++){
bstree.Insert_R(A[i]);
}
bstree.Pre_Order();
BSTreeNode<int>* tmp= bstree.Find(3);
if (tmp==NULL) cout<<"failed\n";
else cout<<tmp->key<<endl;
tmp=bstree.Find_R(5);
if (tmp==NULL) cout<<"failed\n";
else cout<<tmp->key<<endl;
return 0;
}