-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0450-delete-node-in-a-bst.js
42 lines (38 loc) · 1.01 KB
/
0450-delete-node-in-a-bst.js
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
/**
* Recursion
* h = height of the tree;
* Time O(h) | Space O(h)
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} key
* @return {TreeNode}
*/
var deleteNode = function(root, key) {
if (!root) return root;
if (key === root.val) {
if (!root.left) return root.right;
if (!root.right) return root.left;
// find the smallest val in right bst
let curr = root.right;
while (curr.left) {
curr = curr.left;
}
// change the curr value
root.val = curr.val;
root.right = deleteNode(root.right, root.val);
return root;
}
if (key < root.val) {
root.left = deleteNode(root.left, key);
return root;
}
root.right = deleteNode(root.right, key);
return root;
};