-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathBinaryTree.java
More file actions
60 lines (46 loc) · 1.08 KB
/
BinaryTree.java
File metadata and controls
60 lines (46 loc) · 1.08 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
public class BinaryTree{
private static class Node {
Item reg ;
Node left , right ;
}
private Node root;
private long comparisons;
public BinaryTree(){
this.root = null;
this.comparisons = 0;
}
public Item search (Item reg){
return this.search(reg , this.root);
}
public void insert(Item reg){
this.root = this.insert(reg , this.root);
}
public long getComparisons(){
return this.comparisons;
}
//search for an Item and count how many comparisons were made.
private Item search(Item reg , Node p){
this.comparisons++;
if(p == null)
return null;
else if(reg.compare(p.reg) < 0)
return search(reg , p.left);
else if(reg.compare(p.reg) > 0)
return search(reg , p.right);
else return p.reg;
}
private Node insert(Item reg , Node p){
if(p == null){
p = new Node();
p.reg = reg;
p.left = null;
p.right = null;
}
else if(reg.compare(p.reg) < 0)
p.left = insert(reg, p.left);
else if(reg.compare(p.reg) > 0)
p.right = insert(reg , p.right);
else System.out.println("Error: This register already exists");
return p;
}
}