-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0450-delete-node-in-a-bst.js
More file actions
36 lines (33 loc) · 1.01 KB
/
0450-delete-node-in-a-bst.js
File metadata and controls
36 lines (33 loc) · 1.01 KB
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
/**
* Delete Node In A Bst
* Time Complexity: O(H)
* Space Complexity: O(H)
*/
var deleteNode = function (root, key) {
if (!root) {
return null;
}
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 === null) {
return root.right;
} else if (root.right === null) {
return root.left;
} else {
const findMinimumNodeInSubtree = (subtreeRoot) => {
let currentNodeIterator = subtreeRoot;
while (currentNodeIterator.left !== null) {
currentNodeIterator = currentNodeIterator.left;
}
return currentNodeIterator;
};
let inOrderSuccessor = findMinimumNodeInSubtree(root.right);
root.val = inOrderSuccessor.val;
root.right = deleteNode(root.right, inOrderSuccessor.val);
}
}
return root;
};