Repository navigation
Expand file tree
/
Copy pathbinaryTreeSearch.cpp
More file actions
111 lines (88 loc) · 2.27 KB
/
Copy pathbinaryTreeSearch.cpp
File metadata and controls
111 lines (88 loc) · 2.27 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
108
109
110
111
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = NULL;
right = NULL;
}
};
Node* insert(Node* root, int val) {
if (root == NULL)
return new Node(val);
if (root->data < val)
root->right = insert(root->right, val);
else
root->left = insert(root->left, val);
return root;
}
bool search(Node* root, int val) {
if (root == NULL)
return false;
if (root->data == val)
return true;
if (root->data < val)
return search(root->right, val);
return search(root->left, val);
}
Node* getSuccessor(Node* curr) {
curr = curr->right;
while (curr != NULL && curr->left != NULL)
curr = curr->left;
return curr;
}
void del_Node(Node* &root, int val) {
if (root == NULL)
return;
if (root->data > val) {
del_Node(root->left, val);
}
else if (root->data < val) {
del_Node(root->right, val);
}
else {
if (root->left == NULL) {
Node* temp = root->right;
delete root;
root = temp;
}
else if (root->right == NULL) {
Node* temp = root->left;
delete root;
root = temp;
}
else {
Node* succ = getSuccessor(root);
root->data = succ->data;
del_Node(root->right, succ->data);
}
}
}
void in_Order(Node* root) {
if (root == NULL) return;
in_Order(root->left);
cout << root->data << " ";
in_Order(root->right);
}
int main() {
Node* root = new Node(50); // Creating the following BST
insert(root, 30); // 50
insert(root, 20); // / \
insert(root, 40); // 30 70
insert(root, 70); // / \ / \
insert(root, 60); // 20 40 60 80
insert(root, 80);
in_Order(root);
cout << endl;
cout << endl;
cout << (search(root, 70) ? "70 is Found" : "70 is Not Found") << endl;
cout << (search(root, 19) ? "19 is Found" : "19 is Not Found") << endl;
cout << endl;
del_Node(root, 80);
in_Order(root);
return 0;
}