-
Notifications
You must be signed in to change notification settings - Fork 1
/
DeleteNodeInABST.java
58 lines (49 loc) · 1.57 KB
/
DeleteNodeInABST.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.smlnskgmail.jaman.leetcodejava.medium;
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
// https://leetcode.com/problems/delete-node-in-a-bst/
public class DeleteNodeInABST {
private final TreeNode root;
private final int key;
public DeleteNodeInABST(TreeNode root, int key) {
this.root = root;
this.key = key;
}
public TreeNode solution() {
return deleteNode(root, key);
}
private TreeNode deleteNode(TreeNode root, int key) {
if (root != 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 && root.right == null) {
root = null;
} else if (root.right != null) {
root.val = successor(root);
root.right = deleteNode(root.right, root.val);
} else {
root.val = predecessor(root);
root.left = deleteNode(root.left, root.val);
}
}
return root;
}
return null;
}
private int successor(TreeNode node) {
node = node.right;
while (node.left != null) {
node = node.left;
}
return node.val;
}
private int predecessor(TreeNode node) {
node = node.left;
while (node.right != null) {
node = node.right;
}
return node.val;
}
}