If x is greater than the value of a node, floor (x) may be on the right or floor (x ). You only need to find the value less than or equal to x in the right subtree.
The Code is as follows:
Public Key floor (Key key) {return floor (root, key);} private Key floor (Node node, Key key) {if (node = null) return null; int compare = key. compareTo (node. key); // if the node value is the same as the key, the node is the floor value if (compare = 0) return node. key; // if the key is smaller than the node, the floor value must be on the left of the node. If (compare <0) return floor (node. left, key); // if the key is greater than the node, the floor value must be on the right of the node. Key k = floor (node. right, key); if (k! = Null) return k; return node. key ;}
Size operation
The size operation is used to count the number of nodes in a tree to facilitate select and rank operations.
To implement the size operation, you need to add the count member variable to the node to count the number of nodes.
class Node { Key key; Value value; Node left; Node right; int count;}
The size function code is as follows:
private int size(Node node) { if(node == null) return 0; else return node.count;}
You need to modify the put operation to record parent. count.
Private Node put (Node parent, Key key, Value value) {// if parent is empty, create a new Node if (parent = null) {Node node = new Node (); node. key = key; node. value = value; node. count = 1; return node;} // recursively insert int compare = key. compareTo (parent. key); if (compare <0) {parent. left = put (parent. left, key, value); // note: the return value must be assigned to the parent. left} else if (compare> 0) {parent. right = put (parent. right, key, value);} else {parent. value = value;} parent. count = 1 + size (parent. left) + size (parent. right); return parent ;}
Rank operation
The rank operation is to find the ranking of a key in the set.
It is very convenient to implement the recursive method.
public int rank(Key key) { return rank(root, key);} private int rank(Node node, Key key) { if(node == null) { return 0; } int compare = key.compareTo(node.key); if(compare < 0) { return rank(node.left, key); } else if(compare > 0) { return size(node.left) + 1 + rank(node.right, key); } else { return size(node.left); }}
Keys operation
The keys operation extracts all keys in order.
For each node, obtain all the keys of the Left node, their own keys, and all the keys of the right node. That is, the middle-order traversal.
public Iterable
inorder() { Queue
q = new LinkedList
(); inorder(root, q); return q;} private void inorder(Node node, Queue
q) { if(node == null) return; inorder(node.left, q); q.add(node.key); inorder(node.right, q);}
Complexity
For the Binary Search Tree, the complexity of all operations is the same, and the complexity is directly proportional to the height of the tree.