-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBT.java
More file actions
98 lines (95 loc) · 2.03 KB
/
BT.java
File metadata and controls
98 lines (95 loc) · 2.03 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
97
98
package ds;
public class BT<T> {
BTNode<T> root, current;
/** Creates a new instance of BT */
public BT() {
root = current = null;
}
public boolean empty(){
return root == null;
}
public T retrieve() {
return current.data;
}
public void update(T val) {
current.data = val;
}
public boolean insert(Relative rel, T val) {
switch(rel) {
case Root:
if(!empty())
return false;
current = root = new BTNode<T>(val);
return true;
case Parent: // This is an impossible case.
return false;
case LeftChild:
if(current.left != null)
return false;
current.left = new BTNode<T>(val);
current = current.left;
return true;
case RightChild:
if(current.right != null)
return false;
current.right = new BTNode<T> (val);
current = current.right;
return true;
default:
return false;
}
}
public void deleteSubtree(){
if(current == root){
current = root = null;
}
else {
BTNode<T> p = current;
find(Relative.Parent);
if(current.left == p)
current.left = null;
else
current.right = null;
current = root;
}
}
public boolean find(Relative rel){
switch (rel) {
case Root: // Easy case
current = root;
return true;
case Parent:
if(current == root)
return false;
current = findparent(current, root);
return true;
case LeftChild:
if(current.left == null)
return false;
current = current.left;
return true;
case RightChild:
if(current.right == null)
return false;
current = current.right;
return true;
default:
return false;
}
}
private BTNode<T> findparent(BTNode<T> p, BTNode<T> t) {
if(t == null)
return null; // empty tree
if(t.right == null && t.left == null)
return null;
else if(t.right == p || t.left == p)
return t; // parent is t
else {
BTNode<T> q = findparent(p, t.left);
if (q != null)
return q;
else
return findparent(p, t.right);
}
}
}