-
Notifications
You must be signed in to change notification settings - Fork 366
/
binarySearchTree.cpp
102 lines (89 loc) · 2.1 KB
/
binarySearchTree.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
#include <iostream>
class BinarySearchTree {
private:
struct TreeNode {
int value;
TreeNode* left;
TreeNode* right;
};
TreeNode* root;
void insert(int val, TreeNode*& node) {
if (node == nullptr) {
node = new TreeNode{val, nullptr, nullptr};
} else if (val < node->value) {
insert(val, node->left);
} else {
insert(val, node->right);
}
}
bool search(int val, TreeNode* node) {
if (node == nullptr) {
return false;
} else if (val == node->value) {
return true;
} else if (val < node->value) {
return search(val, node->left);
} else {
return search(val, node->right);
}
}
void deleteNode(int val, TreeNode*& node) {
if (node == nullptr) {
return;
} else if (val < node->value) {
deleteNode(val, node->left);
} else if (val > node->value) {
deleteNode(val, node->right);
} else {
if (node->left == nullptr && node->right == nullptr) {
delete node;
node = nullptr;
} else if (node->left == nullptr) {
TreeNode* temp = node;
node = node->right;
delete temp;
} else if (node->right == nullptr) {
TreeNode* temp = node;
node = node->left;
delete temp;
} else {
int temp = findMin(node->right);
node->value = temp;
deleteNode(temp, node->right);
}
}
}
int findMin(TreeNode* node) {
if (node->left == nullptr) {
return node->value;
} else {
return findMin(node->left);
}
}
public:
BinarySearchTree() : root(nullptr) {}
void insert(int val) {
insert(val, root);
}
bool search(int val) {
return search(val, root);
}
void deleteNode(int val) {
deleteNode(val, root);
}
};
int main() {
BinarySearchTree tree;
tree.insert(5);
tree.insert(3);
tree.insert(7);
tree.insert(2);
tree.insert(4);
tree.insert(6);
tree.insert(8);
std::cout << tree.search(3) << std::endl; // True
std::cout << tree.search(9) << std::endl; // False
tree.deleteNode(3);
std::cout << tree.search(3) << std::endl; // False
return 0;
}