-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdeletebst.java
134 lines (107 loc) · 2.59 KB
/
deletebst.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
class Node
{
int data;
Node left = null, right = null;
Node(int data) {
this.data = data;
}
}
class deletebst
{
public static void inorder(Node root)
{
if (root == null) {
return;
}
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
public static Node getMinimumKey(Node curr)
{
while (curr.left != null) {
curr = curr.left;
}
return curr;
}
public static Node insert(Node root, int key)
{
if (root == null) {
return new Node(key);
}
if (key < root.data) {
root.left = insert(root.left, key);
}
else {
root.right = insert(root.right, key);
}
return root;
}
public static Node deleteNode(Node root, int key)
{
Node parent = null;
Node curr = root;
while (curr != null && curr.data != key)
{
parent = curr;
if (key < curr.data) {
curr = curr.left;
}
else {
curr = curr.right;
}
}
if (curr == null) {
return root;
}
if (curr.left == null && curr.right == null)
{
if (curr != root)
{
if (parent.left == curr) {
parent.left = null;
}
else {
parent.right = null;
}
}
else {
root = null;
}
}
else if (curr.left != null && curr.right != null)
{
Node successor = getMinimumKey(curr.right);
int val = successor.data;
deleteNode(root, successor.data);
curr.data = val;
}
else {
// choose a child node
Node child = (curr.left != null)? curr.left: curr.right;
if (curr != root)
{
if (curr == parent.left) {
parent.left = child;
}
else {
parent.right = child;
}
}
else {
root = child;
}
}
return root;
}
public static void main(String[] args)
{
int[] keys = { 15, 10, 20, 8, 12, 16 };
Node root = null;
for (int key: keys) {
root = insert(root, key);
}
root = deleteNode(root, 16);
inorder(root);
}
}