Skip to content

Commit cb5db18

Browse files
authored
Create 450-delete-node-in-a-bst.js
1 parent eb79ad0 commit cb5db18

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

450-delete-node-in-a-bst.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @param {number} key
11+
* @return {TreeNode}
12+
*/
13+
const deleteNode = function(root, key) {
14+
if(root == null) return null
15+
if (root.val > key) {
16+
root.left = deleteNode(root.left, key)
17+
} else if(root.val < key) {
18+
root.right = deleteNode(root.right, key)
19+
} else {
20+
if (root.left == null) {
21+
return root.right
22+
}
23+
if (root.right == null) {
24+
return root.left
25+
}
26+
let rightSmallest = root.right
27+
while(rightSmallest.left != null) rightSmallest = rightSmallest.left
28+
rightSmallest.left = root.left
29+
return root.right
30+
}
31+
return root
32+
};

0 commit comments

Comments
 (0)