假设节点内数据类型为Integer。
public class SearchTree<E extends Comparable<? super E>> { public static class BinaryNode<E> { BinaryNode(E e) { this(e, null, null); } BinaryNode(E e, BinaryNode<E> lt, BinaryNode<E> rt) { this.e = e; this.lt = lt; this.rt = rt; } E e; BinaryNode<E> lt; BinaryNode<E> rt; } private BinaryNode<Integer> root; public SearchTree() { this.root = null; } public void makeEmpty() { this.root = null; } public boolean isEmpty() { return root == null; } private boolean contains(int x, BinaryNode<Integer> t) { if(t == null) return false; int compareResult = new Integer(x).compareTo(t.e); if(compareResult < 0) return contains(x, t.lt); else if(compareResult > 0) return contains(x, t.rt); else return true; } public boolean contains(int x) { return contains(x, root); } //递归方式查找最小 private BinaryNode<Integer> findMin(BinaryNode<Integer> t) { if(t == null) return null; else if(t.lt == null) return t; else return findMin(t.lt); } public int findMin() throws Exception { if(isEmpty()) throw new Exception(); return findMin(root).e; } //非递归查找最大 private BinaryNode<Integer> findMax(BinaryNode<Integer> t) { if(t != null) { while(t.rt != null) t = t.rt; } return t; } public int findMax() throws Exception { if(isEmpty()) throw new Exception(); return findMax(root).e; } private BinaryNode<Integer> insert(int x, BinaryNode<Integer> t) { if(t == null) return new BinaryNode<Integer>(x); int compareResult = new Integer(x).compareTo(t.e); if(compareResult < 0) t.lt = insert(x, t.lt); else if(compareResult > 0) t.rt = insert(x, t.rt); return t; } public void insert(int x) { root = insert(x, root); } private BinaryNode<Integer> remove(int x, BinaryNode<Integer> t) { if(t == null) return t; int compareResult = new Integer(x).compareTo(t.e); if(compareResult < 0) t.lt = remove(x, t.lt); else if(compareResult > 0) t.rt = remove(x, t.rt); else if(t.lt != null && t.rt != null) { t.e = findMin(t.rt).e; t.rt = remove(t.e.intValue(), t.rt); } else t = (t.lt != null) ? t.lt : t.rt; return t; } public void remove(int x) { root = remove(x, root); } private void printTree(BinaryNode<Integer> t) { if(t == null) return; printTree(t.lt); System.out.print(t.e.intValue()); printTree(t.rt); } public void printTree() { printTree(root); } }