-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDeleteNodeInBST.java
More file actions
52 lines (44 loc) · 1.46 KB
/
DeleteNodeInBST.java
File metadata and controls
52 lines (44 loc) · 1.46 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package binary_search_tree;
/**
* Description: https://leetcode.com/problems/delete-node-in-a-bst
* Difficulty: Medium
* Time complexity: O(h)
* Space complexity: O(h)
*/
public class DeleteNodeInBST {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return null;
if (root.val > key) {
// delete in the left subtree
root.left = deleteNode(root.left, key);
} else if (root.val < key) {
// delete in the right subtree
root.right = deleteNode(root.right, key);
} else {
// delete current
if (root.left == null) return root.right;
if (root.right == null) return root.left;
// take one step to the right and go all the way to the left to find successor
TreeNode successorParent = root;
TreeNode successor = root.right;
while (successor.left != null) {
successorParent = successor;
successor = successor.left;
}
if (successor == root.right) {
successor.left = root.left;
return successor;
}
successorParent.left = successor.right;
successor.left = root.left;
successor.right = root.right;
return successor;
}
return root;
}
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
}
}