Delete Node in a BST LeetCode solution in C++

1
class Solution {
2
public:
3
TreeNode *deleteNode(TreeNode *root, int key) {
4
if (root)
5
if (key < root->val)
6
root->left = deleteNode(root->left, key); // We frecursively call the function
7
// until we find the target node
8
else if (key > root->val)
9
root->right = deleteNode(root->right, key);
10
else {
11
if (!root->left && !root->right) return NULL; // No child condition
12
if (!root->left || !root->right)
13
return root->left ? root->left : root->right; // One child contion -> replace the node
14
// with it's child Two child condition
15
TreeNode *temp = root->left; //(or) TreeNode *temp = root->right;
16
while (temp->right != NULL)
17
temp = temp->right; // while(temp->left != NULL) temp = temp->left;
18
root->val = temp->val; // root->val = temp->val;
19
root->left = deleteNode(root->left,
20
temp->val); // root->right = deleteNode(root->right, temp);
21
}
22
return root;
23
}
24
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0