privateclassNode{ private Key key; // sorted by key private Value val; // associated data private Node left, right; // left and right subtrees privateint size; // number of nodes in subtree
publicNode(Key key, Value val, int size){ this.key = key; this.val = val; this.size = size; } }
// 向上取整 public Key ceiling(Key key){ if (key == null) thrownew IllegalArgumentException("argument is null"); if (isEmpty()) thrownew NoSuchElementException("empty symbol table"); Node x = ceiling(root, key); if (x == null) returnnull; elsereturn x.key; }
private Node ceiling(Node x, Key key){ if (x == null) returnnull; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) { Node t = ceiling(x.left, key); if (t != null) return t; elsereturn x; } return ceiling(x.right, key); }
// 选择 public Key select(int k){ if (k < 0 || k >= size()) { thrownew IllegalArgumentException("argument is invalid: " + k); } Node x = select(root, k); return x.key; }
// Return key of rank k. private Node select(Node x, int k){ if (x == null) returnnull; int t = size(x.left); if (t > k) return select(x.left, k); // 选择右子树时,需要扣除左子树中的节点总数 elseif (t < k) return select(x.right, k-t-1); elsereturn x; }
// 排名 publicintrank(Key key){ if (key == null) thrownew IllegalArgumentException("argument is null"); return rank(key, root); }
// Number of keys in the subtree less than key. privateintrank(Key key, Node x){ if (x == null) return0; int cmp = key.compareTo(x.key); if (cmp < 0) return rank(key, x.left); // 排名右子树时,需要加上左子树的节点总数 elseif (cmp > 0) return1 + size(x.left) + rank(key, x.right); elsereturn size(x.left); }