-
Notifications
You must be signed in to change notification settings - Fork 0
/
157.BSTDeleteNode.cpp
86 lines (77 loc) · 2.34 KB
/
157.BSTDeleteNode.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
// Approach : We search for the node to be deleted in the BST, if it is found then we remove the left subtree of the node and connect it
// to the leftmost node in the right subtree, since according to the rules of a BST the left subtree must have smaller values than right
// subtree and the smallest value larger than the largest value in the left subtree of the deleted node is present in the leftmost node
// of the right subtree, vice versa is also true.
#include <iostream>
using namespace std;
struct node{
int data;
struct node* left;
struct node* right;
node(int x) {
data = x;
left = NULL;
right = NULL;
}
};
void connect(struct node* rChild, struct node* lChild) {
if(rChild -> left == NULL) {
rChild -> left = lChild;
return;
}
connect(rChild -> left, lChild);
}
struct node* deleteNode(struct node* root, int key) {
if(root == NULL) {
return NULL;
}
if(root -> data == key) {
if(root -> right == NULL and root -> left == NULL) {
return NULL;
}
if(root -> right == NULL and root -> left != NULL) {
return root -> left;
}
if(root -> right != NULL and root -> left == NULL) {
return root -> right;
}
connect(root -> right, root -> left);
root -> left = NULL;
return root -> right;
}
if(root -> data > key) {
root -> left = deleteNode(root -> left, key);
}
else {
root -> right = deleteNode(root -> right, key);
}
return root;
}
void inorder(struct node* root) {
if(root == NULL) {
return;
}
inorder(root -> left);
cout << root -> data << " ";
inorder(root -> right);
}
int main() {
struct node* root = new node(8);
root -> left = new node(4);
root -> left -> left = new node(2);
root -> left -> left -> left = new node(1);
root -> left -> left -> right = new node(3);
root -> left -> right = new node(6);
root -> left -> right -> left = new node(5);
root -> left -> right -> right = new node(7);
root -> right = new node(12);
root -> right -> left = new node(10);
root -> right -> left -> left = new node(9);
root -> right -> left -> right = new node(11);
root -> right -> right = new node(14);
root -> right -> right -> left = new node(13);
root -> right -> right -> right = new node(15);
root = deleteNode(root, 7);
inorder(root);
return 0;
}