-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTree.java
More file actions
72 lines (63 loc) · 1.32 KB
/
Copy pathTree.java
File metadata and controls
72 lines (63 loc) · 1.32 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
import java.util.*;
public class Tree
{
TreeNode root;
public Tree() {
}
public void insert(String elem) {
root = insert(root, elem);
}
public TreeNode insert(TreeNode t, String elem) {
if (t == null) {
return new TreeNode(elem);
}
if (elem.compareTo(t.data) > 0) {
t.right = insert(t.right, elem);
}
else {
t.left = insert(t.left, elem);
}
return t;
}
public boolean search(String elem) {
return search(root, elem);
}
public boolean search(TreeNode t, String elem) {
if (t == null){
return false;
}
if (t.data.equals(elem)) {
return true;
}
if (elem.compareTo(t.data) < 0){
return search(t.left, elem);
}
else {
return search(t.right, elem);
}
}
public TreeNode build(TreeNode t) {
// make a balanced tree
Vector<TreeNode> nodes = new Vector<TreeNode>();
storeNodes(t, nodes);
return buildRecursion(nodes, 0, nodes.size()-1);
}
public TreeNode buildRecursion(Vector<TreeNode> n, int start, int end) {
if (start > end) {
return null;
}
int mid = (start+end)/2;
TreeNode node = n.get(mid);
node.left = buildRecursion(n, start, mid-1);
node.right = buildRecursion(n, mid+1, end);
return node;
}
public void storeNodes(TreeNode t, Vector<TreeNode> n) {
if (t == null) {
return;
}
storeNodes(t.left, n);
n.add(t);
storeNodes(t.right, n);
}
}