Skip to content

Commit de9d4d2

Browse files
authored
Update 450-delete-node-in-a-bst.js
1 parent 5fc8bd8 commit de9d4d2

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

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

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,45 @@ const deleteNode = function(root, key) {
3131

3232
return root
3333
};
34+
35+
// another
36+
37+
/**
38+
* Definition for a binary tree node.
39+
* function TreeNode(val, left, right) {
40+
* this.val = (val===undefined ? 0 : val)
41+
* this.left = (left===undefined ? null : left)
42+
* this.right = (right===undefined ? null : right)
43+
* }
44+
*/
45+
/**
46+
* @param {TreeNode} root
47+
* @param {number} key
48+
* @return {TreeNode}
49+
*/
50+
const deleteNode = function(root, key) {
51+
if(root == null) return root
52+
53+
if(root.val < key) root.right = deleteNode(root.right, key)
54+
else if(root.val > key) root.left = deleteNode(root.left, key)
55+
else {
56+
if(root.left == null && root.right === null) root = null
57+
else if(root.left == null) root = root.right
58+
else if(root.right == null) root = root.left
59+
else {
60+
const min = findMin(root.right)
61+
root.val = min.val
62+
root.right = deleteNode(root.right, root.val)
63+
}
64+
}
65+
66+
return root
67+
};
68+
69+
function findMin(node) {
70+
let cur = node
71+
while(cur.left) {
72+
cur = cur.left
73+
}
74+
return cur
75+
}

0 commit comments

Comments
 (0)