Skip to content

Commit 600e1d9

Browse files
authored
Update 450-delete-node-in-a-bst.js
1 parent 35b9564 commit 600e1d9

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed

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

+17-16
Original file line numberDiff line numberDiff line change
@@ -11,22 +11,23 @@
1111
* @return {TreeNode}
1212
*/
1313
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)
14+
if(root == null) return null
15+
if(key < root.val) {
16+
root.left = deleteNode(root.left, key)
17+
} else if(key > root.val) {
18+
root.right = deleteNode(root.right, key)
19+
} else {
20+
if(root.left == null) {
21+
return root.right
22+
} else if(root.right == null) {
23+
return root.left
1924
} 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
25+
let smallestRight = root.right
26+
while(smallestRight.left !== null) smallestRight = smallestRight.left
27+
smallestRight.left = root.left
28+
return root.right
3029
}
31-
return root
30+
}
31+
32+
return root
3233
};

0 commit comments

Comments
 (0)