-
Notifications
You must be signed in to change notification settings - Fork 55
/
BST.java
84 lines (71 loc) · 1.93 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
// Aum Amma
import java.util.ArrayDeque;
public class BST {
protected BSTNode root;
public void insert(int key) {
if (root == null)
root = new BSTNode(key);
else
root.insert(key);
}
public void inorder() {
if (root == null)
return;
else
root.inorder();
System.out.println();
}
public void preorder() {
if (root == null)
return;
else
root.preorder();
System.out.println();
}
public void postorder() {
if (root == null)
return;
else
root.postorder();
System.out.println();
}
public boolean search(int key) {
if (root == null)
return false;
else
return root.search(key);
}
public void delete(int key) {
if (root == null)
return;
else if (root.data != key)
root.delete(key);
else { // root.data == key
// Special case implementation - courtesy Deepak Naik
BSTNode dummy = new BSTNode(); // Doesn't matter what data it has
dummy.left = root;
root = dummy; // Make dummy the root
root.delete(key); // This deletes the original root which is to the left of dummy
root = root.left; // Remove dummy to get the real root back
}
}
public void levelorder() {
ArrayDeque<BSTNode> deq = new ArrayDeque<BSTNode>();
deq.addLast(root);
while ( !deq.isEmpty() ) { // until queue is not empty
BSTNode n = deq.removeFirst();
System.out.print(n.data + " ");
if (n.left != null)
deq.addLast(n.left);
if (n.right != null)
deq.addLast(n.right);
}
System.out.println();
}
public int height() {
if (root == null)
return 0;
else
return root.height();
}
}