-
Notifications
You must be signed in to change notification settings - Fork 0
/
cBinarySearchTree.h
127 lines (109 loc) · 2.77 KB
/
cBinarySearchTree.h
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
#include "cNode.h"
#include <iostream>
using namespace std;
template <typename T>
class cBinarySearchTree{
friend class cNode<T>;
public:
cBinarySearchTree() {root = NULL;}
~cBinarySearchTree() {}
void treeInsert(T x);
void treeDelete(T x);
void treePrint();
cNode<T>* treeSearch(cNode<T>* t, T x);
private:
cNode<T>* treeInsert(cNode<T>* t, T x);
void treeDelete(cNode<T>* t, cNode<T>* r, cNode<T>* p);
cNode<T>* deleteNode(cNode<T>* r);
void treePrint(cNode<T>* t, int step);
cNode<T>* root;
};
template<typename T>
cNode<T>* cBinarySearchTree<T>::treeSearch(cNode<T>* t, T x){
if(t == NULL || t->key == x) return t;
if( x< t->key) return treeSearch(t->left, x);
else return treeSearch(t->right, x);
}
template <typename T>
cNode<T>* cBinarySearchTree<T>::treeInsert(cNode<T>* t, T x){
if(t == NULL){
cNode<T>* r;
r=new cNode<T>;
r->key = x;
r->right = NULL;
r->left = NULL;
return r;
}
if(x < t->key){
t->left=treeInsert(t->left, x);
return t;
}
else{
t->right=treeInsert(t->right, x);
return t;
}
}
template <typename T>
void cBinarySearchTree<T>::treeDelete(cNode<T>* t, cNode<T>* r, cNode<T>* p){
if(r == t)
root = deleteNode(t);
else if(r == p->left)
p->left = deleteNode(r);
else
p->right = deleteNode(r);
}
template <typename T>
cNode<T>* cBinarySearchTree<T>::deleteNode(cNode<T>* r){
if(r->left == NULL && r->right == NULL)
return NULL;
else if(r->left == NULL && r->right != NULL)
return r->right;
else if(r->left != NULL && r->right == NULL)
return r->left;
else{
cNode<T>* s;
cNode<T>* parent;
s = r->right;
while(s->left != NULL) {
parent = s;
s = s->left;
}
r->key = s->key;
if(s == r->right)
r->right = s->right;
else
parent->left = s->right;
return r;
}
}
template <typename T>
void cBinarySearchTree<T>::treeInsert(T x){
root = treeInsert(root, x);
}
template <typename T>
void cBinarySearchTree<T>::treeDelete(T x){
cNode<T>* r = root;
cNode<T>* p = 0;
while(r!=0){
if(r->key == x) break;
p = r;
if(x < r->key) r = r->left;
else r = r->right;
}
if(r) treeDelete(root, r, p);
}
template <typename T>
void cBinarySearchTree<T>::treePrint(){
treePrint(root, 0);
}
template <typename T>
void cBinarySearchTree<T>::treePrint(cNode<T>* t, int step)
{
if( t != NULL ) {
for(int i=0; i<step; i++)
cout<<" ";
cout << t->key << endl;
treePrint(t->left, step+1);
treePrint(t->right, step+1);
}
}