Skip to content

Commit 8d299bb

Browse files
authoredAug 6, 2024
Create 0450-delete-node-in-a-bst.js
1 parent 44b0e00 commit 8d299bb

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
 

Diff for: ‎javascript/0450-delete-node-in-a-bst.js

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Recursion
3+
* h = height of the tree;
4+
* Time O(h) | Space O(h)
5+
* Definition for a binary tree node.
6+
* function TreeNode(val, left, right) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.left = (left===undefined ? null : left)
9+
* this.right = (right===undefined ? null : right)
10+
* }
11+
*/
12+
/**
13+
* @param {TreeNode} root
14+
* @param {number} key
15+
* @return {TreeNode}
16+
*/
17+
var deleteNode = function(root, key) {
18+
if(!root) return root;
19+
20+
if(key === root.val) {
21+
if(!root.left) return root.right;
22+
if(!root.right) return root.left;
23+
24+
// find the smallest val in right bst
25+
let curr = root.right;
26+
while(curr.left) {
27+
curr = curr.left;
28+
}
29+
// change the curr value
30+
root.val = curr.val;
31+
32+
root.right = deleteNode(root.right, root.val);
33+
} else if(key < root.val) {
34+
root.left = deleteNode(root.left, key);
35+
} else {
36+
root.right = deleteNode(root.right, key);
37+
}
38+
39+
return root;
40+
};

0 commit comments

Comments
 (0)