forked from Gaurang2908/HacktoberFest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BST.java
96 lines (86 loc) · 2.38 KB
/
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
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
public class BST {
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
private Node root;
public BST() {
root = null;
}
public void insert(int key) {
if (root == null) {
root = new Node(key);
} else {
insertnode(this.root, key);
}
}
public Node insertnode(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
} else if (key < root.key) {
root.left = insertnode(root.left, key);
} else {
root.right = insertnode(root.right, key);
}
return root;
}
public Node deletenode(Node root, int k) {
if (root == null)
return root;
if (root.key > k) {
root.left = deletenode(root.left, k);
return root;
} else if (root.key < k) {
root.right = deletenode(root.right, k);
return root;
}
if (root.left == null) {
Node temp = root.right;
return temp;
} else if (root.right == null) {
Node temp = root.left;
return temp;
} else {
Node succParent = root;
Node succ = root.right;
while (succ.left != null) {
succParent = succ;
succ = succ.left;
}
if (succParent != root)
succParent.left = succ.right;
else
succParent.right = succ.right;
root.key = succ.key;
return root;
}
}
public void Inorder() {
Inorderrec(this.root);
}
public void Inorderrec(Node root) {
if (root != null) {
Inorderrec(root.left);
System.out.print(root.key + " ");
Inorderrec(root.right);
}
}
public static void main(String[] args) {
BST b = new BST();
b.insert(10);
b.insert(12);
b.insert(1);
b.insert(100);
System.out.println("Before Delete");
b.Inorder();
b.deletenode(b.root, 12);
System.out.println();
System.out.println("After Delete");
b.Inorder();
}
}