Skip to content

Commit ca2c275

Browse files
Update 0450-delete-node-in-a-bst.java
The earlier code provided wasn't working for all cases. I have edited the code.
1 parent 40e983b commit ca2c275

File tree

1 file changed

+14
-22
lines changed

1 file changed

+14
-22
lines changed

java/0450-delete-node-in-a-bst.java

Lines changed: 14 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,24 @@
1-
/**
2-
* TC : log (n)
3-
*
4-
* */
51
class Solution {
6-
public TreeNode minimumVal(TreeNode root) {
7-
TreeNode curr = root;
8-
while (curr != null && curr.left != null) {
9-
curr = curr.left;
2+
public TreeNode findMin(TreeNode node) {
3+
TreeNode current = node;
4+
while (current.left != null) {
5+
current = current.left;
106
}
11-
return curr;
7+
return current;
128
}
139

1410
public TreeNode deleteNode(TreeNode root, int key) {
1511
if (root == null) return null;
1612

17-
if (key > root.val) {
18-
root.right = deleteNode(root.right, key);
19-
} else if (key < root.val) {
20-
root.left = deleteNode(root.left, key);
21-
} else {
22-
if (root.left == null) {
23-
return root.right;
24-
} else if (root.right == null) {
25-
return root.left;
26-
} else {
27-
TreeNode minVal = minimumVal(root);
28-
root.val = minVal.val;
29-
root.right = deleteNode(root.right, minVal.val);
13+
if (root.val > key) root.left = deleteNode(root.left, key);
14+
else if (root.val < key) root.right = deleteNode(root.right, key);
15+
else {
16+
if (root.left == null) return root.right;
17+
else if (root.right == null) return root.left;
18+
else {
19+
TreeNode successor = findMin(root.right);
20+
root.val = successor.val;
21+
root.right = deleteNode(root.right, successor.val);
3022
}
3123
}
3224
return root;

0 commit comments

Comments
 (0)