-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path200511V_lab.cpp
More file actions
110 lines (96 loc) · 2.38 KB
/
Copy path200511V_lab.cpp
File metadata and controls
110 lines (96 loc) · 2.38 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
#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 *root, int key) {
// Create a new node
struct node *newNode = new node;
newNode->key = key;
newNode->left = newNode->right = NULL;
// If the tree is empty, return the new node
if (root == NULL) {
return newNode;
}
// Otherwise, recur down the tree
if (key < root->key) {
root->left = insertNode(root->left, key);
} else if (key > root->key) {
root->right = insertNode(root->right, key);
}
// Return the (unchanged) root node
return root;
}
// Deleting a node
struct node *deleteNode(struct node *root, int key) {
// Base case
if (root == NULL) {
return root;
}
// Recur down the tree
if (key < root->key) {
root->left = deleteNode(root->left, key);
} else if (key > root->key) {
root->right = deleteNode(root->right, key);
} else {
// Case 1: Node has no children
if (root->left == NULL && root->right == NULL) {
delete root;
root = NULL;
}
// Case 2: Node has one child
else if (root->left == NULL) {
struct node *temp = root;
root = root->right;
delete temp;
} else if (root->right == NULL) {
struct node *temp = root;
root = root->left;
delete temp;
}
// Case 3: Node has two children
else {
struct node *temp = root->right;
while (temp->left != NULL) {
temp = temp->left;
}
root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
}
return root;
}
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);
}