-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdelete-a-node-from-bst.java
More file actions
69 lines (60 loc) · 1.92 KB
/
delete-a-node-from-bst.java
File metadata and controls
69 lines (60 loc) · 1.92 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.util.*;
public class DeleteNodeBST {
public static void main(String[] args) {
Node root = new Node(12);
// MAKE A TREE OF NODES...
delete(root, 14);
}
public static Node delete(Node root, int data) {
// base case, tree is empty
if (root == null) {
return root;
}
// 1.A node is in left subtree
// set root's leftchild to result of delete(root.left...)
else if (data < root.data) {
root.left = delete(root.left, data);
}
// 1.B node is in right subtree
// set root's righth child to result of delete(root.right...)
else if (data > root.data) {
root.right = delete(root.right, data);
}
// 2 found data!
else {
// Case 1: no child
// just set node to null (remove it) and return it
if (root.left == null && root.right == null) {
root = null;
}
// Case 2: one child
// 2.A: no left child
else if (root.left == null) {
Node temp = root;
root = root.right;
temp = null;
}
// 2.B: no right child
else if (root.right == null) {
Node temp = root;
root = root.left;
temp = null;
}
// Case 3: 2 children
else {
// get minimum element in right subtree
// set it to `root` and remove it from its
// original spot
Node temp = findMin(root.right);
root.data = temp.data;
root.right = delete(root.right, temp.data);
}
}
return root;
}
public static Node findMin(Node root) {
while (root.left != null)
root = root.left;
return root;
}
}