-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path450. Delete Node in a BST (Leetcode)
33 lines (33 loc) · 1.09 KB
/
450. Delete Node in a BST (Leetcode)
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
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root == nullptr) return nullptr;
if(key < root -> val) root -> left = deleteNode(root -> left, key);
else if(key > root -> val) root -> right = deleteNode(root -> right, key);
else {
if(root -> left == nullptr && root -> right == nullptr) {
delete(root);
root = nullptr;
}
else if(root -> left == nullptr) {
TreeNode *temp = root;
root = root -> right;
delete(temp);
}
else if(root -> right == nullptr) {
TreeNode *temp = root;
root = root -> left;
delete(temp);
}
else {
TreeNode *temp = root -> right;
while(temp -> left != nullptr) {
temp = temp -> left;
}
root -> val = temp -> val;
root -> right = deleteNode(root -> right, temp -> val);
}
}
return root;
}
};