Skip to content

Instantly share code, notes, and snippets.

@songpp
Created April 2, 2011 07:11
Show Gist options
  • Save songpp/899303 to your computer and use it in GitHub Desktop.
Save songpp/899303 to your computer and use it in GitHub Desktop.
JAVA BinaryTree
package t1;
public class JavaBinaryTree{
static class Empty extends BinaryTreeMap{
protected Empty(){}
@Override
public boolean isEmpty(){
return true;
}
@Override
public String toString(){
return "Nil";
}
}
private static BinaryTreeMap Nil = new Empty();
private static class BinaryTreeMap<K extends Comparable<K>, V> {
private K key;
private V value;
private BinaryTreeMap<K, V> left;
private BinaryTreeMap<K, V> right;
private BinaryTreeMap(){}
public boolean isEmpty() {
return false;
}
public BinaryTreeMap(K k, V v, BinaryTreeMap<K, V> l, BinaryTreeMap<K, V> r) {
key = k;
value = v;
left = l;
right = r;
}
public BinaryTreeMap<K, V> insert(K k, V val) {
if(isEmpty())
return new BinaryTreeMap<K,V>(k,val,Nil,Nil);
if (k.compareTo(key) == 0)
return this;
else if (k.compareTo(key) > 0)
return new BinaryTreeMap<K, V>(key, value, left, right.insert(k, val));
else
return new BinaryTreeMap<K, V>(key, value, left.insert(k, val), right);
}
public String toString() {
return String.format("[ [Tree] (Key : %s), (value : %s), (left : %s), (right : %s) ]", key, value,left,right);
}
public V search(K key) {
return null;
}
public V getValue() {
return value;
}
}
static <K extends Comparable<K>, V> BinaryTreeMap<K, V> makeTree(K key,
V value) {
return new BinaryTreeMap<K, V>(key, value, Nil, Nil);
}
public static void main(String[] args) {
BinaryTreeMap<String, String> tree = makeTree("123", "123");
tree = tree.insert("234", "234");
tree = tree.insert("345", "234");
tree = tree.insert("012", "234");
System.out.println(tree);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment