-
Notifications
You must be signed in to change notification settings - Fork 0
/
delete-node-in-a-bst.js
46 lines (41 loc) · 1.16 KB
/
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
43
44
45
46
/**
* 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 === null)
return root;
if (key > root.val) {
root.right = deleteNode(root.right, key);
}
else if (key < root.val) {
root.left = deleteNode(root.left, key);
}
else {
// found the key
// has children
if (root.left !== null && root.right !== null) {
let min = new TreeNode();
min = root.right;
while (min.left !== null) min = min.left;
root.val = min.val;
root.right = deleteNode(root.right, min.val);
} else {
// no children
let newRoot = new TreeNode();
newRoot = root.left === null ? root.right : root.left;
root.left = root.right = null;
return newRoot;
}
}
return root;
};