-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearchTree.cpp
More file actions
107 lines (95 loc) · 2.03 KB
/
binarySearchTree.cpp
File metadata and controls
107 lines (95 loc) · 2.03 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
98
99
100
101
102
103
104
105
106
107
typedef struct Node {
int key;
struct Node* left;
struct Node* right;
Node() {
left = nullptr;
right = nullptr;
}
};
Node* insert(Node* x, int y) {
if (x == nullptr) {
Node* returnValue = new Node;
returnValue->key = y;
return returnValue;
} else if (x->key > y) {
x->left = insert(x->left, y);
} else if (x->key < y) {
x->right = insert(x->right, y);
}
return x;
}
Node* minimum(Node* x) {
if (x->left == nullptr) {
return x;
}
return minimum(x->left);
}
Node* maximum(Node* x) {
if (x->right == nullptr) {
return x;
}
return maximum(x->right);
}
Node* search(Node* x, int y) {
if (x == nullptr || y == x->key) {
return x;
}
if (y < x->key) {
return search(x->left, y);
} else {
return search(x->right, y);
}
}
Node* next(Node* root, int x) {
Node* current = root;
Node* successor = nullptr;
while (current != nullptr) {
if (current->key > x) {
successor = current;
current = current->left;
} else {
current = current->right;
}
}
return successor;
}
Node* prev(Node* root, int x) {
Node* current = root;
Node* successor = nullptr;
while (current != nullptr) {
if (current->key < x) {
successor = current;
current = current->right;
} else {
current = current->left;
}
}
return successor;
}
Node* remove(Node* root, int x) {
if (root == nullptr) {
return root;
}
if (root->key > x) {
root->left = remove(root->left, x);
} else if (root->key < x) {
root->right = remove(root->right, x);
} else {
if (root->left == nullptr && root->right == nullptr) {
return nullptr;
} else if (root->left == NULL) {
Node* returnValue = root->right;
delete root;
return returnValue;
} else if (root->right == nullptr) {
Node* returnValue = root->left;
delete root;
return returnValue;
}
Node* tmp = minimum(root->right);
root->key = tmp->key;
root->right = remove(root->right, tmp->key);
}
return root;
}