17 public TreeNode(K key, V value, TreeNode<K, V> left, TreeNode<K, V> right) {
49public class BinarySearchTree<K
extends Comparable<K>, V>
51 private TreeNode<K, V> root;
53 public BinarySearchTree() { root =
null; }
58 public void insert(K key, V value)
throws DuplicateException {
59 root = insert(root, value, key);
62 private TreeNode<K, V> insert(TreeNode<K, V> n, V value, K key)
throws DuplicateException {
64 return new TreeNode<K, V>(key, value,
null,
null);
67 if (n.getKey().equals(key)) {
68 throw new DuplicateException();
71 if (key.compareTo(n.getKey()) < 0) {
73 n.setLeft( insert(n.getLeft(), value, key) );
79 n.setRight( insert(n.getRight(), value, key) );
86 public void delete(K key) {
87 root = delete(root, key);
91 private K smallest(TreeNode<K, V> n)
96 if (n.getLeft() ==
null) {
99 return smallest(n.getLeft());
103 private TreeNode<K, V> delete(TreeNode<K, V> n, K key)
109 if (key.equals(n.getKey())) {
111 if (n.getLeft() ==
null && n.getRight() ==
null) {
114 if (n.getLeft() ==
null) {
117 if (n.getRight() ==
null) {
122 K smallVal = smallest(n.getRight());
124 n.setRight( delete(n.getRight(), smallVal) );
128 else if (key.compareTo(n.getKey()) < 0) {
129 n.setLeft( delete(n.getLeft(), key) );
134 n.setRight( delete(n.getRight(), key) );
141 public boolean lookup(K key) {
142 return lookup(root, key);
145 private boolean lookup(TreeNode<K, V> n, K key) {
150 if (n.getKey().equals(key)) {
154 if (key.compareTo(n.getKey()) < 0) {
156 return lookup(n.getLeft(), key);
161 return lookup(n.getRight(), key);