forked from kbeathanabhotla/DSAAJ2-Answers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChap04.text.02.BinarySearchTree.java
More file actions
110 lines (93 loc) · 2.86 KB
/
Copy pathChap04.text.02.BinarySearchTree.java
File metadata and controls
110 lines (93 loc) · 2.86 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
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
//Chap04.text.02.BinarySearchTree.java
public class BinarySearchTree<T extends Comparable<? super T>> {
private static class BinaryTreeNode<T> {
T data;
BinaryTreeNode<T> left, right;
BinaryTreeNode(BinaryTreeNode<T> l, T d, BinaryTreeNode<T> r) {
left = l;
data = d;
right = r;
}
}
private BinaryTreeNode<T> root;
public BinarySearchTree() {
root = null;
}
public void makeEmpty() {
root = null;
}
public boolean isEmpty() {
return root == null;
}
public boolean contains(T t) {
return contains(t, root);
}
private boolean contains(T t, BinaryTreeNode<T> root) {
if (root == null) return false;
int compareResult = t.compareTo(root.data);
if (compareResult < 0)
return contains(t, root.left);
else if (compareResult > 0)
return contains(t, root.right);
else
return true;
}
public T findMin() {
if (root == null) return null;
while (root.left != null)
root = root.left;
return root.data;
}
public T findMax() {
if (root == null) return null;
while (root.right != null)
root = root.right;
return root.data;
}
public void insert(T t) {
root = insert(t, root);
}
private BinaryTreeNode<T> insert(T t, BinaryTreeNode<T> root) {
if (root == null)
return new BinaryTreeNode<T>(null, t, null);
int compareResult = t.compareTo(root.data);
if (compareResult < 0)
root.left = insert(t, root.left);
else if (compareResult > 0)
root.right = insert(t, root.right);
return root;
}
public void remove(T t) {
root = remove(t, root);
}
private BinaryTreeNode<T> remove(T t, BinaryTreeNode<T> root) {
if (root == null)
return null;
int compareResult = t.compareTo(root.data);
if (compareResult < 0)
root.left = remove(t, root.left);
else if (compareResult > 0)
root.right = remove(t, root.right);
else if (root.left != null && root.right != null) {
BinaryTreeNode<T> rightMin = root.right;
while (rightMin.left != null)
rightMin = rightMin.left;
root.data = rightMin.data;
root.right = remove(rightMin.data, root.right);
} else
root = root.left != null ? root.left : root.right;
return root;
}
public void printTree() {
printTree(root);
}
private void printTree(BinaryTreeNode<T> root) {
if (root == null)
System.out.print("# ");
else {
System.out.print(root.data + " ");
printTree(root.left);
printTree(root.right);
}
}
}