-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbst.cpp
More file actions
121 lines (111 loc) · 2.22 KB
/
bst.cpp
File metadata and controls
121 lines (111 loc) · 2.22 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
112
113
114
115
116
117
118
119
120
121
#include<iostream>
#define SPACES 10;
using namespace std;
struct tree {
int value;
tree *left, *right;
tree(int v) {
value = v;
left = NULL;
right = NULL;
}
};
void inorder(tree *t) {
if(t != NULL) {
inorder(t->left);
cout << t->value;
inorder(t->right);
}
}
tree *minValueNode(tree *root) {
tree* current = root;
while (current && current->left != NULL)
current = current->left;
return current;
}
tree* insert(tree *root, int x) {
if(root == NULL) {
root = new tree(x);
} else {
if(x < root->value) {
if(root->left == NULL) {
root->left = new tree(x);
} else {
root->left = insert(root->left, x);
}
} else if (x > root->value) {
if(root->right == NULL) {
root->right = new tree(x);
} else {
root->right = insert(root->right, x);
}
}
}
return root;
}
tree* deleteNode(tree *root, int x) {
if(root == NULL) {
cout << "Node not found.";
} else {
if(x == root->value) {
if(root->left == NULL) {
tree *t = root->right;
delete root;
return t;
} else if(root->right == NULL) {
tree *t = root->left;
delete root;
return t;
} else {
tree *t = minValueNode(root->right);
root->value = t->value;
root->right = deleteNode(root->right, t->value);
}
} else if(x < root->value) {
root->left = deleteNode(root->left, x);
} else if (x > root->value) {
root->right = deleteNode(root->right, x);
}
}
return root;
}
void displayTree(tree *root, int space = 0) {
if(!(root == NULL)) {
space += SPACES;
displayTree(root->right, space);
cout << endl;
int i = SPACES;
for (; i < space; i++) {
cout<<" ";
}
cout << root->value;
displayTree(root->left, space);
}
}
int main() {
tree *root = NULL;
int ch,n;
do {
cout << "\n1.Insert Node\n2.Delete Node\n3.Display Tree\n0. Exit\nEnter your choice: ";
cin >> ch;
switch(ch){
case 1:
cout << "\nEnter value of node:";
cin >> n;
if(root==NULL)
root=insert(root,n);
else
insert(root,n);
break;
case 2:
cout << "\nEnter value to be deleted: ";
cin >> n;
root=deleteNode(root,n);
break;
case 3:
displayTree(root);
break;
}
} while (ch != 0);
return 0;
}