-
Notifications
You must be signed in to change notification settings - Fork 0
/
delete_node_bst.cpp
42 lines (38 loc) · 1.08 KB
/
delete_node_bst.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
class Solution {
public:
TreeNode* inorder_successor(TreeNode* root){
TreeNode* p = root;
while(p && p->left){
p = p->left;
}
return p;
}
TreeNode* deleteNode(TreeNode* root, int key) {
if(!root){
return root;
}
if(key < root->val){
root->left = deleteNode(root->left, key);
}
else if(key > root->val){
root->right = deleteNode(root->right, key);
}
else if(key == root->val){
if(!root->left){
TreeNode* temp = root->right;
delete root->left;
return temp;
}
else if(!root->right){
TreeNode* temp = root->left;
delete root->right;
return temp;
}
TreeNode* temp = inorder_successor(root->right);
//get inorder succesor
root->val = temp->val;
root->right = deleteNode(root->right, temp->val);
}
return root;
}
};