-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTree.java
More file actions
96 lines (74 loc) · 1.55 KB
/
Copy pathBinarySearchTree.java
File metadata and controls
96 lines (74 loc) · 1.55 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
package com.java.ds.bst;
import java.util.Comparator;
public class BinarySearchTree<T extends Comparable<T>> {
Node<T> root;
Comparator<T> compr;
public BinarySearchTree() {
}
public BinarySearchTree(Comparator<T> compr) {
this.compr = compr;
}
public void add(T t) {
if (root == null) {
root = new Node<T>(t);
} else {
add(root, t);
}
}
private void add(Node<T> root, T t) {
int compare;
if (compr != null) {
compare = compr.compare(root.value, t);
} else {
compare = t.compareTo(root.value);
}
if (compare > 0) {// right
if (root.getRight() == null) {
Node<T> node = new Node<T>(t);
root.setRight(node);
} else {
add(root.getRight(), t);
}
} else if (compare < 0) { // left
if (root.getLeft() == null) {
Node<T> node = new Node<T>(t);
root.setLeft(node);
} else {
add(root.getLeft(), t);
}
}
}
public void iterateAsc(){
travelTreeAsc(root);
}
private void travelTreeAsc(Node<T> root) {
if (root != null) {
travelTreeAsc(root.getLeft());
System.out.print(root.getValue() + "-");
travelTreeAsc(root.getRight());
}
}
private static class Node<T extends Comparable<T>> {
private T value;
private Node<T> left;
private Node<T> right;
public Node(T t) {
this.value = t;
}
public void setLeft(Node<T> left) {
this.left = left;
}
public void setRight(Node<T> right) {
this.right = right;
}
public T getValue() {
return value;
}
public Node<T> getLeft() {
return left;
}
public Node<T> getRight() {
return right;
}
}
}