106 lines
2.7 KiB
Java
106 lines
2.7 KiB
Java
|
public class TreeNode<K,V> {
|
||
|
|
||
|
private K key;
|
||
|
private V value;
|
||
|
|
||
|
private TreeMap<K, V> tree;
|
||
|
private TreeNode<K, V> sub;
|
||
|
private TreeNode<K, V> top;
|
||
|
|
||
|
public TreeNode(TreeMap<K, V> tree, K key, V value) {
|
||
|
this.key = key;
|
||
|
this.value = value;
|
||
|
}
|
||
|
|
||
|
public K getKey() {
|
||
|
return key;
|
||
|
}
|
||
|
|
||
|
public V getValue() {
|
||
|
return value;
|
||
|
}
|
||
|
|
||
|
public V put(K key, V value) {
|
||
|
int comparison = tree.getComparator().compare(this.key, key);
|
||
|
|
||
|
if (comparison == -1) {
|
||
|
if (sub == null) sub = new TreeNode<K,V>(tree, key, value);
|
||
|
else sub.put(key, value);
|
||
|
return null;
|
||
|
} else if (comparison == 0) {
|
||
|
V oldValue = this.value;
|
||
|
this.value = value;
|
||
|
return oldValue;
|
||
|
} else {
|
||
|
if (top == null) top = new TreeNode<K,V>(tree, key, value);
|
||
|
else top.put(key, value);
|
||
|
return null;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public V get(K key) {
|
||
|
int comparison = tree.getComparator().compare(this.key, key);
|
||
|
|
||
|
if (comparison == -1) {
|
||
|
if (sub == null) return null;
|
||
|
else return sub.get(key);
|
||
|
} else if (comparison == 0) {
|
||
|
return value;
|
||
|
} else {
|
||
|
if (top == null) return null;
|
||
|
else return top.get(key);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public boolean containsKey(K key) {
|
||
|
int comparison = tree.getComparator().compare(this.key, key);
|
||
|
|
||
|
if (comparison == -1) {
|
||
|
if (sub == null) return false;
|
||
|
else return sub.containsKey(key);
|
||
|
} else if (comparison == 0) {
|
||
|
return true;
|
||
|
} else {
|
||
|
if (top == null) return false;
|
||
|
else return top.containsKey(key);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public TreeNode<K, V> getSub() {
|
||
|
return sub;
|
||
|
}
|
||
|
|
||
|
public TreeNode<K, V> getTop() {
|
||
|
return top;
|
||
|
}
|
||
|
|
||
|
public V remove(K key) {
|
||
|
int comparison = tree.getComparator().compare(this.key, key);
|
||
|
|
||
|
if (comparison == -1) {
|
||
|
if (sub == null) return null;
|
||
|
else {
|
||
|
if (tree.getComparator().compare(key, sub.getKey()) == 0) {
|
||
|
V value = sub.getValue();
|
||
|
sub = null;
|
||
|
|
||
|
return value;
|
||
|
} else {
|
||
|
return sub.remove(key);
|
||
|
}
|
||
|
}
|
||
|
} else {
|
||
|
if (top == null) return null;
|
||
|
else {
|
||
|
if (tree.getComparator().compare(key, top.getKey()) == 0) {
|
||
|
V value = top.getValue();
|
||
|
top = null;
|
||
|
return value;
|
||
|
} else {
|
||
|
return top.remove(key);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|