-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST (2).cpp
More file actions
97 lines (83 loc) · 2.01 KB
/
BST (2).cpp
File metadata and controls
97 lines (83 loc) · 2.01 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>
using namespace std;
struct node {
int key;
struct node *left, *right;
};
// Inorder traversal
void traverseInOrder(struct node *root) {
if (root != NULL) {
traverseInOrder(root->left);
cout << root->key << " ";
traverseInOrder(root->right);
}}
// Insert a node
struct node *insertNode(struct node *node, int key) {
if (node == NULL) {
struct node *new_Node = new struct node;
new_Node->key = key;
new_Node->left = new_Node->right = NULL;
return new_Node;
}
if (key <= node->key ) {
node->left = insertNode(node->left, key);
} else if (key >= node->key ) {
node->right = insertNode(node->right, key);
}
return node;
}
// Deleting a node
struct node *deleteNode(struct node *root, int key) {
if (root == NULL) {
return root;
}
if (key < root->key and root->left!=NULL) {
root->left = deleteNode(root->left, key);
} else if (key > root->key and root -> right!=NULL) {
root->right = deleteNode(root->right, key);
} else {
// Node with one child
if (root->left == NULL) {
struct node *temp = root->right;
delete root;
return temp;
} else if (root->right == NULL) {
struct node *temp = root->left;
delete root;
return temp;
}
// parent with 2 children
struct node *temp = root->right;
while (temp && temp->left != NULL) {
temp = temp->left;
}
root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
return root;
}
// Driver code
int main() {
struct node *root = NULL;
int operation;
int operand;
cin >> operation;
while (operation != -1) {
switch(operation) {
case 1: // insert
cin >> operand;
root = insertNode(root, operand);
cin >> operation;
break;
case 2: // delete
cin >> operand;
root = deleteNode(root, operand);
cin >> operation;
break;
default:
cout << "Invalid Operator!\n";
return 0;
}
}
traverseInOrder(root);
}