Successor and Predecessor
The successor of a node is the node with the smallest key larger than : the node that follows in the inorder walk. The predecessor is the one before it. A hash table cannot answer this question without a full scan; a BST answers it in time without comparing a single key, using only the shape of the tree and the parent pointers. That is what makes ordered iteration, range queries and the deletion procedure of the next lesson work.
The two cases
Think of the inorder walk at the moment it prints . What does it print next?
- has a right subtree. The walk continues with that subtree, and the first thing it prints there is the subtree's minimum. So the successor is TREE-MINIMUM.
- has no right subtree. Then the walk has finished the subtree rooted at , and also every subtree in which was the last node printed. Climb from towards the root as long as you come up from a right child; the first time you arrive from a left child, the node you arrive at is printed next. If you reach the root without that happening, was the maximum and has no successor.
In case 2 the successor is the lowest ancestor of whose left child is also an ancestor of (where counts as its own ancestor). Every node on the climb before is smaller than (we came up from their right subtrees), and itself is larger than everything in its left subtree, including .
TREE-SUCCESSOR(x)
1 if x.right != NIL
2 return TREE-MINIMUM(x.right) // case 1: leftmost node of the right subtree
3 y = x.parent
4 while y != NIL and x == y.right // case 2: climb while coming from a right child
5 x = y
6 y = y.parent
7 return yTREE-PREDECESSOR is the mirror image: the maximum of the left subtree, or the lowest ancestor reached from a right child. Both procedures follow a single path, down in case 1 and up in case 2, so they take time.
class Node:
__slots__ = ("key", "left", "right", "parent")
def __init__(self, key):
self.key, self.left, self.right, self.parent = key, None, None, None
def insert(root, key):
z, y, x = Node(key), None, root
while x is not None:
y, x = x, (x.left if key < x.key else x.right)
z.parent = y
if y is None: return z
if key < y.key: y.left = z
else: y.right = z
return root
def find(x, k):
while x is not None and x.key != k:
x = x.left if k < x.key else x.right
return x
def successor(x, trace):
if x.right is not None:
x = x.right
trace.append(f"right to {x.key}")
while x.left is not None:
x = x.left
trace.append(f"left to {x.key}")
return x
y = x.parent
while y is not None and x is y.right:
trace.append(f"up from right child to {y.key}")
x, y = y, y.parent
trace.append(f"up from left child to {y.key}" if y else "past the root: none")
return y
def predecessor(x):
if x.left is not None:
x = x.left
while x.right is not None: x = x.right
return x
y = x.parent
while y is not None and x is y.left:
x, y = y, y.parent
return y
root = None
for k in [41, 20, 65, 11, 29, 50, 91, 32, 72, 99, 26]:
root = insert(root, k)
for k in [20, 32, 50, 99]:
trace = []
s = successor(find(root, k), trace)
p = predecessor(find(root, k))
print(f"successor of {k:2}: {s.key if s else None!s:4} ({'; '.join(trace)}) predecessor: {p.key if p else None}")successor of 20: 26 (right to 29; left to 26) predecessor: 11
successor of 32: 41 (up from right child to 29; up from right child to 20; up from left child to 41) predecessor: 29
successor of 50: 65 (up from left child to 65) predecessor: 41
successor of 99: None (up from right child to 91; up from right child to 65; up from right child to 41; past the root: none) predecessor: 91
The tree is the one from Binary Search Trees: Searching, Minimum and Maximum. For 20 the right subtree exists (case 1); for 32 the climb passes 29 and 20 from the right and stops at 41 (case 2); 99 is the maximum.
In C++
std::map iterators move with exactly this procedure: ++it on a red-black tree node is TREE-SUCCESSOR. The C++ version below implements it on an index-based tree and walks the whole tree with it.
#include <cstdio>
#include <vector>
struct BST {
struct Node { int key, left = -1, right = -1, parent = -1; };
std::vector<Node> t;
int root = -1;
void insert(int key) {
int y = -1, x = root;
while (x != -1) { y = x; x = key < t[x].key ? t[x].left : t[x].right; }
int z = static_cast<int>(t.size());
t.push_back({key, -1, -1, y});
if (y == -1) root = z; else if (key < t[y].key) t[y].left = z; else t[y].right = z;
}
int minimum(int x) const { while (t[x].left != -1) x = t[x].left; return x; }
int successor(int x) const {
if (t[x].right != -1) return minimum(t[x].right);
int y = t[x].parent;
while (y != -1 && x == t[y].right) { x = y; y = t[y].parent; }
return y;
}
};
int main() {
BST b;
for (int k : {41, 20, 65, 11, 29, 50, 91, 32, 72, 99, 26}) b.insert(k);
std::printf("in order via successor:");
for (int x = b.minimum(b.root); x != -1; x = b.successor(x)) std::printf(" %d", b.t[x].key);
std::printf("\n");
}in order via successor: 11 20 26 29 32 41 50 65 72 91 99
Walking the whole tree costs , not
A full traversal "minimum, then successor times" makes calls of each, which suggests . The true cost is : every edge of the tree is traversed exactly twice, once going down and once coming up. An edge from down to a child is descended when the walk enters that child's subtree, and climbed when it leaves, and neither happens again. A tree with nodes has edges, so the total is at most steps plus the initial descent to the minimum, which is part of the same count.
The program counts the pointer steps of a full successor walk on a random tree, a zigzag tree of height 999 and a sorted path. The count is exactly for every shape.
import random
class Node:
__slots__ = ("key", "left", "right", "parent")
def __init__(self, key):
self.key, self.left, self.right, self.parent = key, None, None, None
def insert(root, key):
z, y, x = Node(key), None, root
while x is not None:
y, x = x, (x.left if key < x.key else x.right)
z.parent = y
if y is None: return z
if key < y.key: y.left = z
else: y.right = z
return root
steps = 0
def minimum(x):
global steps
while x.left is not None:
x = x.left; steps += 1
return x
def successor(x):
global steps
if x.right is not None:
steps += 1
return minimum(x.right)
y = x.parent
while y is not None and x is y.right:
x, y = y, y.parent; steps += 1
steps += 1 if y is not None else 0
return y
def height(root): # iterative: the zigzag tree is 999 levels deep
best, stack = -1, [(root, 0)]
while stack:
x, d = stack.pop()
if x is not None:
best = max(best, d)
stack += [(x.left, d + 1), (x.right, d + 1)]
return best
rng = random.Random(4)
for name, keys in [("random 1000", rng.sample(range(10 ** 6), 1000)), ("zigzag 1000", [i // 2 if i % 2 == 0 else 999 - i // 2 for i in range(1000)]), ("sorted 500", list(range(500)))]:
root = None
for k in keys:
root = insert(root, k)
steps, out = 0, []
x = minimum(root)
while x is not None:
out.append(x.key); x = successor(x)
assert out == sorted(keys)
n = len(keys)
print(f"{name:12}: n = {n}, height {height(root):3}, pointer steps {steps}, 2(n - 1) = {2 * (n - 1)}")random 1000 : n = 1000, height 20, pointer steps 1998, 2(n - 1) = 1998
zigzag 1000 : n = 1000, height 999, pointer steps 1998, 2(n - 1) = 1998
sorted 500 : n = 500, height 499, pointer steps 998, 2(n - 1) = 998
Range queries
The same idea answers "list all keys in ": find the smallest key (a search that remembers the last node where it went left), then call TREE-SUCCESSOR until the key exceeds . If keys are reported, the cost is : one descent, then a walk over a contiguous piece of the tree. This is the query that databases answer with B-trees (B-Trees: Definition, Height and Search) and that std::map::lower_bound starts.
class Node:
__slots__ = ("key", "left", "right", "parent")
def __init__(self, key):
self.key, self.left, self.right, self.parent = key, None, None, None
def insert(root, key):
z, y, x = Node(key), None, root
while x is not None:
y, x = x, (x.left if key < x.key else x.right)
z.parent = y
if y is None: return z
if key < y.key: y.left = z
else: y.right = z
return root
def ceiling(x, a): # node with the smallest key >= a, or None
best = None
while x is not None:
if x.key >= a:
best, x = x, x.left # a candidate; look for a smaller one on the left
else:
x = x.right
return best
def successor(x):
if x.right is not None:
x = x.right
while x.left is not None: x = x.left
return x
y = x.parent
while y is not None and x is y.right:
x, y = y, y.parent
return y
def range_query(root, a, b):
out, x = [], ceiling(root, a)
while x is not None and x.key <= b:
out.append(x.key); x = successor(x)
return out
root = None
for k in [41, 20, 65, 11, 29, 50, 91, 32, 72, 99, 26]:
root = insert(root, k)
for a, b in [(25, 60), (0, 15), (92, 98), (60, 100)]:
print(f"keys in [{a}, {b}]: {range_query(root, a, b)}")keys in [25, 60]: [26, 29, 32, 41, 50]
keys in [0, 15]: [11]
keys in [92, 98]: []
keys in [60, 100]: [65, 72, 91, 99]
Test yourself
Node has a right child. Where is its successor?
- at its parent
- at the leftmost node of its right subtree
- at its right child
- at the root
Node has no right child and is the left child of its parent . What is its successor?
- the minimum of the tree
- has none
- the right child of
How many pointer steps does a complete walk (minimum, then successor until NIL) take on an -node BST?
- , at most about
- always