二叉搜索树与平衡树
Binary Search Tree
这一节需要配合快排部分的 partition 思想食用。两个算法之间的 correspondence 真的很奇妙啊!
BST Properties
Definition. A BST is a binary tree in symmetric order.
Symmetric order. Each node has a key, and every node's key is:
- Larger than all keys in its left subtree.
- Smaller than all keys in its right subtree.
Therefore, inorder traversal of a BST yields keys in ascending order.
A node in BST should contain three four fields: key, value, references to left node and right node.
private class Node {
private Key key;
private Value val;
private Node left, right;
public Node(Key key, Value val) {
this.key = key;
this.val = val;
}
}
Note that Key and Value are generic types; Key is Comparable.
Insertion and Deletion
Operation put: Associate value with key.
public void put(Key key, Value val) { root = put(root, key, val); }
private Node put(Node x, Key key, Value val) {
if (x == null) return new Node(key, val);
int cmp = key.compareTo(x.key);
if (cmp < 0)
x.left = put(x.left, key, val);
else if (cmp > 0)
x.right = put(x.left, key, val);
else
x.val = val;
return x;
}
Deletion is BST is much more tricky. The lazy approach is to set tombstones, which easily leads to memory overload. So we introduce Hibbard deletion here.
To delete a node with key k; search for node t containing key k.
- Case 0. [0 children] Delete
tby setting parent link tonull. - Case 1. [1 child] Delete
tby replacing parent link to its child. - Case 2. [2 children] Delete
t's predecessor or successor and replacetwith it.- Find the successor
xoft. - Delete
x, but don't garbage collect it. (xhas no left child, so it will be case 0 or 1) - Put
xint's spot.
- Find the successor
Definition. the neighboring nodes in inorder traversal.
- predecessor: the rightmost node in the left subtree.
- successor: the leftmost node in the right subtree.
public void delete(Key key) { root = delete(root, key); }
public void deleteMin() { root = deleteMin(root); }
private Node deleteMin(Node x) {
if (x.left == null) return x.right;
x.left = deleteMin(x.left);
return x;
}
private Node delete(Node x, Key key) {
if (x == null) return null; // case 0
int cmp = key.compareTo(x.key);
if (cmp < 0)
x.left = delete(x.left, key);
else if (cmp > 0)
x.right = delete(x.right, key);
else {
if (x.right == null) return x.left; // case 1
if (x.left == null) return x.right; // case 1
Node t = x; // case 2
x = min(t.right);
x.right = deleteMin(t.right); // replace t with x, update sons link
x.left = t.left;
}
return x; // replace t with x, update father link
}
Hibbard deletion is NOT symmetric; it may lead to BST degenerating with height
If for every Hibbard deletion, we flip a coin to decide whether replacing t with its predecessor or successor, then the expected height of BST will be
BSTs and Quicksort Partitioning
BSTs highly correspond to quicksort partitioning. Given
Here is the basic idea:
- Set the current partitioning item
a[j]as the root. - Note that
a[lo...j-1]are no larger thana[j], anda[j+1...hi]are no smaller thana[j]; **this corresponds to BST's symmetric order. ** - Set the partitioning item in
[lo, j-1]asa[j]'s left son, and the one in[j+1, hi]as the right son.
Proposition. If
The proof is 1-1 correspondence with quicksort partitioning.
Therefore, we could see that just like the efficiency of quicksort depends on the random shuffle of the items, the efficiency of BST highly depends on the randomness of inserting keys.
If
2-3 Search Trees
接下来我们将介绍两种著名的平衡搜索树 (Balanced Search Tree),2-3 树与红黑树。与二叉搜索树 BST 不同,无论插入的键值顺序是否随机,平衡搜索树总能维持平衡;其树高是稳定的
。 Robert Sedgewick 教授总能把这种复杂的算法讲得深入浅出;之前一直对红黑树望而却步的我第一次理解了其本质:它其实是左倾 2-3 树的二叉树表现形式。(后来我才发现 Sedgewick 教授本人就是红黑树的发明者之一,甚至 Red Black Tree 这个名字也是他参与提出的)
2-3 Tree Properties
2-3 tree allows 1 or 2 keys per node. It consists of two kinds of nodes:
- 2-node: one key, two children.
- 3-node: two keys, three children.
For a 3-node with keys
Therefore, just like BST, the inorder traversal of 2-3 tree yields keys in ascending order.
2-3 tree also achieves perfect balance.
Perfect balance. Every path from root to null link has the same length.
Insertion
When inserting a key into 2-3 tree.
- Find the corresponding bottom node.
- If it is a 2-node at bottom.
- Insert the key into the 2-node so it becomes a 3-node.
- If it is a 3-node at bottom.
- Insert the key into the 3-node to create a temporary 4-node. (contains ascending 3 keys)
- Move middle key in 4-node into parent and split it into two 2-nodes.
- Repeat up the tree as necessary.
- If you reach the root and it's a 4-node, split it into three 2-nodes. (height increases)
Note that each transformation maintains symmetric order and perfect balance; the height of 2-3 tree increases only when every node on the search path from the root is a 3-node.
Performance
Perfect balance of 2-3 trees guarantees logarithmic performance for search and insert.
Tree height.
- Worst case [all 2-nodes]:
. - Best case [all 3-nodes]:
.
The order of growth of symbol table implemented with 2-3 tree is
Red-Black BSTs
We will introduce left-leaning red-black BSTs. It is essentially a representation of 2-3 tree as a BST. In particular, we use internal left-leaning links as "glue" for 3-nodes.
The internal links are marked as red links, while the rest of the links (the external links connecting different nodes) are marked as black links.
We encode color of links in nodes since each node is pointed by precisely one link from its parent.
private static final boolean RED = true;
private static final boolean BLACK = false;
private class Node {
Key key;
Value val;
Node left, right;
boolean color; // color of parent link
}
private boolean isRed(Node x) {
if (x == null) return false;
return x.color == RED;
}
Properties
Red Black Trees is a BST such that:
- No node has two red links connect to it.
- Perfect black balance: Every path from root to null link has the same number of black links.
- Red links lean left.
The above properties could be easily observed due to 1-1 correspondence between 2-3 and LLRB.
- Any 3-node corresponds to only one internal red link.
- 2-3 tree achieves perfect balance.
Elementary operations
Invariants. Maintains symmetric order and perfect black balance.
- Left rotation. Orient a (temporarily) right-leaning red link to lean left.
- Right rotation. Orient a left-leaning red link to (temporarily) lean right.
- Color flip. Recolor to split a (temporary) 4-node.
Left & Right rotation are mirror images of each other; They change the leaning direction of a red link without violating symmetric order and perfect black balance.
Color flip simulates the splitting of a temporary 4-node; for a node with two red son links (they glue it and its sons together), we flip the color of its two son links and its parent link.
private void flipColors(Node h) {
assert !isRed(h);
assert isRed(h.left);
assert isRed(h.right);
h.color = RED;
h.left.color = BLACK;
h.right.color = BLACK;
}
Insertion
The insertion in a LLRB tree maintains 1-1 correspondence with 2-3 trees by applying elementary red-black BST operations.
Case 1. Insert into a 2-node at bottom.
- Do standard BST insert; color new link red.
- If new red link is a right link, rotate left.
Case 2. Insert into a 3-node at bottom.
- DO standart BST insert; color new link red.
- Rotate to balance the 4-node (if needed).
- Flip colors to pass red link up one level.
- Rotate to make lean left (if needed).
- Repeat case 1 or case 2 up the tree (if needed).
See the Java implementation below: this is the code for all cases.
private Node put(Node h, Key key, Value val) {
if (h == null) return new Node(key, val, RED);
int cmp = key.compareTo(h.key);
if (cmp < 0) h.left = put(h.left, key, val);
else if (cmp > 0) h.right = put(h.right, key, val);
else h.val = val;
if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h); // lean left
if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); // balance 4-node
if (isRed(h.left) && isRed(h.right)) flipColors(h); // split 4-node
return h;
}
Performance
Proposition. Height of tree is
Proof (guaranteed by properties).
- Black balance. Every path from root to null link has the same number of black links.
- Never two red links in-a-row.








