-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path450-deleteNodeBST.cpp
More file actions
19 lines (19 loc) · 1.15 KB
/
Copy path450-deleteNodeBST.cpp
File metadata and controls
19 lines (19 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root)
if(key < root->val) root->left = deleteNode(root->left, key); //We frecursively call the function until we find the target node
else if(key > root->val) root->right = deleteNode(root->right, key);
else{
if(!root->left && !root->right) return NULL; //No child condition
if (!root->left || !root->right)
return root->left ? root->left : root->right; //One child contion -> replace the node with it's child
//Two child condition
TreeNode* temp = root->left; //(or) TreeNode *temp = root->right;
while(temp->right != NULL) temp = temp->right; // while(temp->left != NULL) temp = temp->left;
root->val = temp->val; // root->val = temp->val;
root->left = deleteNode(root->left, temp->val); // root->right = deleteNode(root->right, temp);
}
return root;
}
};