public class TreeNode { private T value; private TreeNode lesser; private TreeNode greater; private SearchTree parentTree; public TreeNode(SearchTree parentTree, T object) { this.parentTree = parentTree; this.value = object; } public void add(T object) { switch (parentTree.getComparator().compare(value, object)) { case -1: if (lesser != null) lesser.add(object); else lesser = new TreeNode(parentTree, object); break; case 0: throw new IllegalArgumentException("Value already in tree"); case 1: if (greater != null) greater.add(object); else greater = new TreeNode(parentTree, object); break; } } public void remove(T object) { if (lesser.getValue().equals(object)) { T a = lesser.getLesser().getValue(); T b = lesser.getGreater().getValue(); parentTree.add(a); parentTree.add(b); lesser = null; } else if (greater.getValue().equals(object)) { T a = greater.getLesser().getValue(); T b = greater.getGreater().getValue(); parentTree.add(a); parentTree.add(b); greater = null; } else { switch (parentTree.getComparator().compare(value, object)) { case -1: if (lesser != null) lesser.remove(object); else return; break; case 0: throw new IllegalStateException("Something fucked up"); case 1: if (greater != null) greater.remove(object); else return; break; } } } public T getValue() { return value; } public TreeNode getLesser() { return lesser; } public TreeNode getGreater() { return greater; } @Override public String toString() { String str = ""; if (greater != null) str += greater.toString(); str += value.toString() + " "; if (lesser != null) str += lesser.toString() + " "; return str; } }