forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0450-delete-node-in-a-bst.java
More file actions
34 lines (32 loc) · 915 Bytes
/
0450-delete-node-in-a-bst.java
File metadata and controls
34 lines (32 loc) · 915 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* TC : log (n)
*
* */
class Solution {
public TreeNode minimumVal(TreeNode root) {
TreeNode curr = root;
while (curr != null && curr.left != null) {
curr = curr.left;
}
return curr;
}
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return null;
if (key > root.val) {
root.right = deleteNode(root.right, key);
} else if (key < root.val) {
root.left = deleteNode(root.left, key);
} else {
if (root.left == null) {
return root.right;
} else if (root.right == null) {
return root.left;
} else {
TreeNode minVal = minimumVal(root);
root.val = minVal.val;
root.right = deleteNode(root.right, minVal.val);
}
}
return root;
}
}