-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathdelete-node-in-a-BST.java
42 lines (42 loc) · 1.13 KB
/
delete-node-in-a-BST.java
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public static TreeNode successor(TreeNode cur) {
while (cur.left != null) {
cur = cur.left;
}
return cur;
}
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) {
return root;
}
TreeNode temp = null;
if (key < root.val) {
root.left = deleteNode(root.left, key);
} else if (key > root.val) {
root.right = deleteNode(root.right, key);
} else {
if (root.left == null) {
temp = root.right;
root.right = null;
return temp;
} else if (root.right == null) {
temp = root.left;
root.left = null;
return temp;
}
temp = successor(root.right);
root.val = temp.val;
root.right = deleteNode(root.right, temp.val);
}
return root;
}
}