-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp77_binarySearchTree.cpp
More file actions
99 lines (86 loc) · 1.63 KB
/
Copy pathp77_binarySearchTree.cpp
File metadata and controls
99 lines (86 loc) · 1.63 KB
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
#include <iostream>
#include <cstdio>
struct node{
int val;
node *lch, *rch;
};
// add x
node *insert(node *p, int x){
if(p == NULL){
node *q = new node;
q->val = x;
q->lch = q->rch = NULL;
return q;
}
else {
if(x < p->val) p->lch = insert(p->lch,x);
else p->rch = insert(p->rch, x);
return p;
}
}
// looking for x
bool find(node *p, int x){
if (p == NULL) return false;
else if (x == p->val) return true;
else if (x < p->val) return find(p->lch, x);
else return find(p->rch, x);
}
// delete x
node *remove(node *p, int x){
if (p == NULL) return NULL;
else if (x < p->val) p->lch = remove(p->lch, x);
else if (x > p->val) p->rch = remove(p->rch, x);
else if (p->lch == NULL) {
node *q = p->rch;
delete p;
return q;
}
else if (p->lch->rch == NULL) {
node *q = p->lch;
q->rch = p->rch;
delete p;
return q;
}
else {
node *q;
for (q = p->lch; q->rch->rch != NULL; q = q->rch);
node *r = q->rch;
q->rch = r->lch;
r->lch = p->lch;
r->rch = p->rch;
delete p;
return r;
}
return p;
}
int main(){
node *tree = new node;
tree = NULL;
char input;
int x;
while(1){
std::cout << "i:insert, f:find, r:remove" << std::endl;
std::cin >> input;
if (input == 'i'){
std::cout << "Input num : ";
std::cin >> x;
tree = insert(tree, x);
}
else if (input == 'f'){
std::cout << "Find num : ";
std::cin >> x;
if (find(tree,x))
std::cout << "Found!" << std::endl;
else
std::cout << "Not found" << std::endl;
}
else if (input == 'r'){
std::cout << "Remove num : ";
std::cin >> x;
tree = remove(tree, x);
}
else break;
}
std::cout << std::endl;
return 0;
}