二叉搜索树与平衡树

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.

java
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.

java
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 t by setting parent link to null.
  • Case 1. [1 child] Delete t by replacing parent link to its child.
  • Case 2. [2 children] Delete t's predecessor or successor and replace t with it.
    • Find the successor x of t.
    • Delete x, but don't garbage collect it. (x has no left child, so it will be case 0 or 1)
    • Put x in t's spot.

Definition. the neighboring nodes in inorder traversal.

  • predecessor: the rightmost node in the left subtree.
  • successor: the leftmost node in the right subtree.

An example for Hibbard deletion

java
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 ∼N\sim\sqrt{N}.

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 ∼lg⁡N\sim \lg{N}. (this lacks rigorous mathematics proof)

BSTs and Quicksort Partitioning

BSTs highly correspond to quicksort partitioning. Given NN distinct keys, we could simply build a BST using quicksort partitioning.

Here is the basic idea:

  • Set the current partitioning item a[j] as the root.
  • Note that a[lo...j-1] are no larger than a[j], and a[j+1...hi] are no smaller than a[j]; **this corresponds to BST's symmetric order. **
  • Set the partitioning item in [lo, j-1] as a[j]'s left son, and the one in [j+1, hi] as the right son.

Correspondence between BSTs and quicksort partitioning

Proposition. If NN distinct keys are inserted into a BST in random order, the expected number of compares for a search/insert operation is ∼2ln⁡N\sim 2\ln N.

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 NN distinct keys are inserted in random order, the expected height of BST is ∼4.311ln⁡N\sim4.311\ln{N}. But worst-case height of BST is NN, which means ∼N2\sim N^2 compares are needed for a search/insert.

2-3 Search Trees

接下来我们将介绍两种著名的平衡搜索树 (Balanced Search Tree),2-3 树与红黑树。与二叉搜索树 BST 不同,无论插入的键值顺序是否随机,平衡搜索树总能维持平衡;其树高是稳定的 ∼lg⁡N\sim \lg{N}。

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 ll and rr, the keys in left subtree are <l<l, the keys in middle subtree are between ll and rr, and the keys in right subtree are >r> r.

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.

Note that the keys in 3-node is also in order

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.

The local transformations achieve perfect balance; it does NOT change height

Performance

Perfect balance of 2-3 trees guarantees logarithmic performance for search and insert.

Tree height.

  • Worst case [all 2-nodes]: lg⁡N\lg{N}.
  • Best case [all 3-nodes]: log⁡3N≈.631lg⁡N\log_3{N}\approx .631\lg{N}.

The order of growth of symbol table implemented with 2-3 tree is ∼clg⁡N\sim c\lg{N}; the constants depend upon implementation.

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.

Transfer 3-nodes into BST representation

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.

2-3 tree and corresponding red-black BST

We encode color of links in nodes since each node is pointed by precisely one link from its parent.

java
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:

  1. No node has two red links connect to it.
  2. Perfect black balance: Every path from root to null link has the same number of black links.
  3. Red links lean left.

The above properties could be easily observed due to 1-1 correspondence between 2-3 and LLRB.

  1. Any 3-node corresponds to only one internal red link.
  2. 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.

java
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.

See how "internal" red links corresponds to 3-nodes

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).

Note that in this example the "black height" increases by 1

See the Java implementation below: this is the code for all cases.

java
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 ≤2lg⁡N\leq 2\lg{N} in the worst case.

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.

Height of RB Tree is  in typical applications like symbol table

CC BY-NC-SA 4.0
正在加载评论…