-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDelete Node in a BST.cpp
30 lines (30 loc) Β· 1.5 KB
/
Delete Node in a 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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
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;
}
};