-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDelete Node in BST
49 lines (46 loc) · 1.1 KB
/
Delete Node in BST
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
Node* findLeftRightMost(Node* root){
if(root->right == NULL){
return root;
}
return findLeftRightMost(root->right);
}
Node* helper(Node* root){
if(root->left == NULL){
return root->right;
}
if(root->right == NULL){
return root->left;
}
Node* rightChild = root->right;
Node* leftChild = findLeftRightMost(root->left);
leftChild->right = rightChild;
return root->left;
}
Node *deleteNode(Node *root, int X) {
if(root == NULL){
return NULL;
}
if(root->data == X){
return helper(root);
}
Node* temp = root;
while(root!=NULL){
if(root->data>X){
if(root->left!=NULL && root->left->data == X){
root->left = helper(root->left);
break;
}else{
root = root->left;
}
}else{
if(root->right!=NULL && root->right->data == X){
root->right = helper(root->right);
break;
}
else{
root=root->right;
}
}
}
return temp;
}