-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTree.java
More file actions
50 lines (42 loc) · 1.11 KB
/
Copy pathBinarySearchTree.java
File metadata and controls
50 lines (42 loc) · 1.11 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
public class BinarySearchTree<E extends Comparable<E>> {
private TreeNode<E> root;
private int size = 0;
public BinarySearchTree() {
root = null;
}
public int getSize() {
return size;
}
public void add(E data) {
TreeNode<E> toAdd = new TreeNode<E>(data);
root = add(root, toAdd);
}
private TreeNode<E> add(TreeNode<E> currentRoot, TreeNode<E> toAdd){
if(currentRoot == null) {
size++;
return toAdd;
}
int c = currentRoot.getData().compareTo(toAdd.getData());
if(c < 0) {
currentRoot.setRight(add(currentRoot.getRight(), toAdd));
}else if (c > 0){
currentRoot.setLeft(add(currentRoot.getLeft(), toAdd));
}
return currentRoot;
}
public E search(E findMe) {
return search(root, findMe);
}
private E search(TreeNode<E> currentRoot, E findMe) {
if(currentRoot == null) {
return null;
}// object not in tree
if(findMe.equals(currentRoot.getData())) {
return currentRoot.getData();
}// found the object
if(findMe.compareTo(currentRoot.getData()) < 0) {
return search(currentRoot.getLeft(), findMe);
}
return search(currentRoot.getRight(), findMe);
}
}