-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearchTree.java
114 lines (94 loc) · 2.69 KB
/
BinarySearchTree.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
package dev.sb.edu.algo.trees;
public class BinarySearchTree {
private final Node root;
public BinarySearchTree(int... values) {
assert values != null && values.length > 0 : "invalid conditions";
root = new Node(values[0]);
for (int i = 1; i <= values.length - 1; i++) {
root.insert(new Node(values[i]));
}
}
public void insert(int value) {
root.insert(new Node(value));
}
public boolean contains(int value) {
return root.contains(value);
}
public void printInOrder(){
root.printInOrder();
}
public void printPreOrder() {
root.printPreOrder();
}
public void printPostOrder(){
root.printPostOrder();
}
public static class Node {
private Node left;
private Node right;
private final int value;
public Node(int value) {
this.value = value;
}
public void insert(Node node) {
if (node.value <= this.value) {
if (left == null) {
left = node;
} else {
left.insert(node);
}
} else {
if (right == null) {
right = node;
} else {
right.insert(node);
}
}
}
public boolean contains(int value) {
if (value == this.value) {
return true;
}
// these conditions may be simplified,
// just for verbosity
if (value < this.value) {
if (left == null) {
return false;
}
return left.contains(value);
} else {
if (right == null) {
return false;
}
return right.contains(value);
}
}
public void printInOrder() {
if (left != null){
left.printInOrder();
}
System.out.print(" >> " + this.value);
if (right != null){
right.printInOrder();
}
}
public void printPreOrder() {
System.out.print(" >> " + this.value);
if (left != null){
left.printInOrder();
}
if (right != null){
right.printInOrder();
}
}
public void printPostOrder() {
if (left != null){
left.printInOrder();
}
if (right != null){
right.printInOrder();
}
System.out.print(" >> " + this.value);
}
}
}