ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
Theory of trees

The headers of include/ADS/tree realize the TREE and the binary tree of chapter 5 of the book, with pointers, with cursors, with lists of children and in vectors, and their visits; the binary search trees of chapter 6, plain, balanced by height (AVL), randomized (treaps), self-adjusting (splay trees) and threaded; the algorithms that build the sets and the maps on these trees by joins; the B-trees of the external memory; and, beyond the book, the link-cut trees of the forests that change. This page collects the definitions and the notation that the headers share (see Definitions and notation), the representations of the trees with the costs of their operations (see Representations and their costs), the visits and the problems on binary trees (see Visits and Problems on binary trees), the search trees and the arguments behind their bounds (see Binary search trees), the algorithms by joins (see Join-based algorithms), the B-trees (see B-trees), the dynamic trees (see Dynamic trees), the aggregates that change and the observers that keep them (see Aggregates that change), and the trees of chapters 6 to 9 of Morin, Open Data Structures, with their exercises (from The trees of Open Data Structures to Left-leaning red-black trees). The pseudocode of each operation and of each algorithm is on the page of its header, in the comment of its function, together with the section of the book, or the paper, that it follows.

Definitions and notation

A rooted tree is a set of \( n \) nodes, empty or with one node, the root, and a partition of the others into subtrees whose roots are the children of the root; every node but the root has one parent, and the tree is ordered when the children of each node are in an order, the first being the leftmost (section 5.1 of the book). A binary tree is an ordered tree whose nodes have at most two children, told apart as the left and the right one even when only one is there. A node with no child is a leaf, the others are internal; the depth of a node is the number of edges from the root to it, the nodes of depth \( l \) form the level \( l \), and the height of a tree is the largest depth of its nodes, \( -1 \) for the empty tree.

The symbols of the headers of the area
SymbolMeaning
\( n \)the number of nodes, or of keys
\( h \)the height of a tree
\( T_1 , \ldots , T_k \)the subtrees of the children of a node, in their order
\( p[ i ] \)the parent of the node \( i \) in a vector of parents, -1 (NIL) at a root
\( d \)the degree of a complete \( d \)-ary tree, or the number of children of a node
\( \mathit{bh}( x ) \)the black height of the node \( x \) of a Red-Black tree, the black nodes on a path from \( x \) down to a leaf nil

Representations and their costs

The representations of the ordered and of the binary trees and the cost of their operations (sections 5.2, 5.4 and 5.5 of the book)
RealizationRepresentationParentFirst child, next siblingInsert a childSpace
Treepointers to the parent, the first child and the next sibling\( O( 1 ) \)\( O( 1 ) \)\( O( 1 ) \)\( \Theta( n ) \)
CursorTreethe same links as indices in a vector, with a free list\( O( 1 ) \)\( O( 1 ) \)\( O( 1 ) \) amortized\( \Theta( n ) \)
ChildListTreea list of the children per node, each node with its cell\( O( 1 ) \)\( O( 1 ) \)\( O( 1 ) \) amortized\( \Theta( n ) \)
ParentTreea vector of parents\( O( 1 ) \)none\( O( 1 ) \), no order among the children\( \Theta( n ) \), one integer per node
PreorderArrayTreethe nodes in a vector in preorder, with their parents\( O( 1 ) \)\( O( 1 ) \) and \( O( n ) \)\( O( n ) \)\( \Theta( n ) \)
BinaryTreepointers to the parent and to the two children\( O( 1 ) \)\( O( 1 ) \) (the left and the right child)\( O( 1 ) \)\( \Theta( n ) \)
CursorBinaryTreethe same links as indices in a vector\( O( 1 ) \)\( O( 1 ) \)\( O( 1 ) \) amortized\( \Theta( n ) \)
ArrayBinaryTreea positional vector, the children of \( i \) in \( 2 i + 1 \) and \( 2 i + 2 \)\( O( 1 ) \)\( O( 1 ) \)linear in the subtree copied\( O( 2^h ) \)

The links to the first child and to the next sibling give every ordered tree, whatever the degrees of its nodes, three pointers per node, and they make it a binary tree: the left child of a node is its first child and the right child its next sibling (figure 5.9 of the book, to_binary() of BinaryTree.h), a correspondence one to one between the ordered forests and the binary trees. The vector of parents (section 5.4) needs one integer per node and answers the parent alone, which is what the trees of the visits of a graph and the forests of the MFSET need; in preorder, the same vector knows the children too, the subtree of a node being the stretch of places that starts with it and ends at the first place whose parent precedes it. A complete \( d \)-ary tree needs no link at all: numbered by levels from 0, the children of the node \( i \) are

\[ d i + 1 , \ldots , d i + d , \qquad \text{its parent} \ \lfloor ( i - 1 ) / d \rfloor , \tag{1} \]

which is how a heap is stored (see Theory of priority queues); a binary tree far from complete wastes the places of the missing nodes, up to \( 2^{h+1} - 1 \) places for \( n = h + 1 \) nodes. The cursors put the nodes in one vector, so that the tree can be copied, saved or moved as a whole, and the indices stay valid when the vector grows.

Visits

A visit examines each node of a tree once: the previsit examines a node before its subtrees, the postvisit after them, the invisit with index \( i \) after its first \( i \) subtrees (on a binary tree, with \( i = 1 \), the symmetric visit), and the visit by levels examines the nodes by increasing depth, by a queue (section 5.3).

Lemma 1 (the cost of a visit). Each visit of a tree of \( n \) nodes costs \( \Theta( n ) \) time on the representations with the links to the first child and to the next sibling, or to the two children, and \( O( h ) \) space for its stack, explicit or of the calls.

Indeed, each node is examined once, and each link is followed once from the node it leaves: the first child of a node when the node is entered, the next sibling when its subtree is over. The stack holds the nodes of the path from the root to the current node, i.e., at most \( h + 1 \) of them; the headers keep it explicit, since a tree of height \( n - 1 \) would overflow the stack of the calls.

The visits need no stack at all when the nodes have the link to their parent: the next node in symmetric order of a binary tree is the leftmost node of the right subtree, if there is one, and otherwise the lowest ancestor reached from a left child (inorder() of BinaryTree.h, and PathIterator of Iterators.h, which keeps the path instead of the links to the parents). A whole visit costs \( \Theta( n ) \) even so, since each edge is walked once down and once up, while a single step costs \( O( h ) \). The threads of Perlis and Thornton reach the same end with no link to the parent: a missing left child is replaced by a link to the predecessor and a missing right child by a link to the successor, a bit of each node telling a child from a thread, so that the successor is the right thread or the leftmost node of the right subtree (ThreadedTree). The \( n + 1 \) links that a binary tree of \( n \) nodes leaves nil are exactly the threads.

Problems on binary trees

The functions of BinaryTreeAlgorithms.h work on any representation of the nodes with the links to the children, and to the parent where they need it. Two nodes \( u \) and \( v \) have their lowest common ancestor at the point where the paths from them to the root meet; once the deeper node has climbed to the depth of the other, the two climb together and meet there, i.e., \( O( h ) \) time and \( O( 1 ) \) space. A binary tree is a search tree if and only if each key lies in the open interval that its ancestors leave to it, which a previsit carrying the two ends checks in \( O( n ) \), while comparing each node with its children only is not enough. A search for the keys in \( [ a , b ] \) examines, beside the \( k \) keys reported, only the nodes on the two paths that search for \( a \) and for \( b \), i.e., \( O( h + k ) \) nodes. A sorted vector gives the search tree of least height, \( \lceil \log_2( n + 1 ) \rceil - 1 \), with the middle key at the root and the two halves below, in \( O( n ) \) by \( T( n ) = 2 T( n / 2 ) + O( 1 ) \).

The previsit and the invisit of a binary tree of distinct values determine it, since the first value of the previsit is the root and splits the invisit into the two subtrees; a stack of the nodes whose right subtree is still open rebuilds it in \( O( n ) \), each node pushed and popped once. The Cartesian tree of a vector \( A \) (Vuillemin) has the leftmost minimum of \( A \) at its root and the Cartesian trees of the parts before and after it as its subtrees: it is the only binary tree whose invisit is \( A \) and which is a heap, and a stack of its right spine builds it in \( O( n ) \), since each item is pushed and popped once; the lowest common ancestor of two places in it is the minimum of \( A \) between them, which ties the two problems together (Harel and Tarjan, and the range minimum of RangeMinimum.h).

A heap of \( n \) items is built either by inserting the items one at a time, each climbing to its place (Williams, HeapByInsertion.h), or by sifting down the internal nodes from the last one to the root (Floyd). The insertions cost \( \Theta( n \log n ) \) in the worst case, an increasing vector, where each item climbs to the root, while the bottom-up construction costs \( O( n ) \): the \( \lceil n / 2^{l+1} \rceil \) nodes of height \( l \) go down at most \( l \) levels each, and \( \sum_l l \, n / 2^{l+1} \le n \). On a random permutation the insertions cost \( O( n ) \) on average as well (Hayward and McDiarmid), and they are the method to use when the heap must be valid after each item.

Binary search trees

A binary search tree holds a set of keys in the nodes of a binary tree so that, for every node \( u \), the keys of the left subtree of \( u \) are smaller than the key of \( u \) and those of its right subtree larger (section 6.1 of the book); hence the visit in symmetric order gives the keys in increasing order, and a search, an insertion and a removal go down one path from the root, in \( O( h ) \) time for a tree of height \( h \). The removal of a node with two children puts in its place its successor, the smallest key of its right subtree, which has no left child and is removed in its turn. Inserted in increasing order, \( n \) keys make a path, \( h = n - 1 \); inserted in a random order, the expected depth of a node is \( 2 \ln n + O( 1 ) \), i.e., about \( 1.39 \log_2 n \), by the analysis of the quicksort, whose pivots are the roots of the subtrees. A balanced tree keeps \( h = O( \log n ) \) whatever the order of the operations, by rotations: the right rotation of a node \( x \) with left child \( y \) makes \( y \) the root of the subtree and \( x \) its right child, the right subtree of \( y \) becoming the left one of \( x \), which keeps the order of the keys and changes the depths of the subtrees by \( \pm 1 \), in \( O( 1 ) \) (figure 6.4 of the book).

The successor search, the find( x ) of the sorted set of Morin (section 6.2.1 of his book), returns the smallest key not smaller than \( x \) along the same path: it remembers the last node at which the path turned left, and stops at a key equal to \( x \). The answer is that node. Indeed, a node \( u \) at which the path turns right is smaller than \( x \), and so is its left subtree; a node at which it turns left is not, and its right subtree holds only larger keys; and the nodes of the left turns decrease along the path, each in the left subtree of the previous one; hence the last of them is the least key not smaller than \( x \). lowerBoundNode() of SearchTree gives the node, in \( O( h ) \) like the search, on the sentinel nil of the book; the other binary search trees of the area, but the splay tree, reach it by searchTreeLowerBound() of BinaryTreeAlgorithms.h, the same descent written once on their nodes (as are the search, the access by rank and the rank of a key), and every ordered dictionary of the library gives the same answer by lowerBound(), as a pair, and by lowerBoundKey(), as the address of the key, which makes DictionarySet over it a sorted set [see The sets of Morin's book].

The binary search trees of the area and the cost of their operations
TreeBalanceHeightSearch, insertion, removalRotations per update
BinarySearchTreenone\( n - 1 \) in the worst case\( O( h ) \)none
RedBlackTreecolors, (V1)-(V4)\( \le 2 \log_2( n + 1 ) \)\( O( \log n ) \)at most 3
AVLTreeheights of the children differing by at most 1\( < 1.4405 \log_2( n + 2 ) \)\( O( \log n ) \)\( O( \log n ) \) on a removal, at most 2 on an insertion
Treapa heap of random priorities\( O( \log n ) \) expected\( O( \log n ) \) expectedfewer than 2 expected
SplayTreenone, each access splayed to the root\( n - 1 \) in the worst case\( O( \log n ) \) amortized\( O( \log n ) \) amortized
HashedTreap, FingerTreapa heap of hashed or random priorities\( O( \log n ) \) expected\( O( \log n ) \) expected, a search from a finger \( O( 1 + \log r ) \)fewer than 2 expected
RandomizedSearchTreethe sizes, random choices\( O( \log n ) \) expected\( O( \log n ) \) expectednone, splits and joins
ScapegoatTreenone (or the sizes)\( \le \log_b q \), \( 1 < b < 2 \)\( O( \log n ) \), the updates amortizednone, rebuilds
PartialRebuildingTreethe sizes (and timers)\( O( \log n ) \) (expected for the dynamite tree, after insertions only)\( O( \log n ) \) amortized or expectednone, rebuilds
LeftLeaningRedBlackTreecolors, left-leaning (a 2-4 tree)\( \le 2 \log_2( n + 1 ) \)\( O( \log n ) \)\( O( 1 ) \) amortized
MeasuredSearchTreenone; size, depth, height kept\( n - 1 \) in the worst case\( O( h ) \)none

A Red-Black tree colors its nodes red or black, with (V1) the root black, (V2) the leaves black, (V3) the children of a red node black, and (V4) the same number of black nodes on all the paths from a node to the leaves below it, its black height \( b( u ) \). By induction on the height, the subtree of \( u \) has at least \( 2^{b( u )} - 1 \) internal nodes (Theorem 6.1 of the book), and by (V3) at least half the nodes of a path from the root are black; hence \( n \ge 2^{h / 2} - 1 \), i.e., \( h \le 2 \log_2( n + 1 ) \) (Theorem 6.3). An insertion colors the new node red, which may break (V3) only; the fault climbs by recolorings, two levels at a time, and is solved by at most two rotations. A removal of a black node breaks (V4) on one side, which a black token climbing by recolorings, and solved by at most three rotations, restores.

Lemma 2 (the height of an AVL tree, Adelson-Velsky and Landis). An AVL tree of height \( h \) has at least \( F_{h+3} - 1 \) nodes, \( F_k \) the \( k \)-th number of Fibonacci; hence

\[ h < \log_\varphi\bigl( \sqrt{5} ( n + 2 ) \bigr) - 3 < 1.4405 \log_2( n + 2 ) , \tag{2} \]

\( \varphi = ( 1 + \sqrt{5} ) / 2 \) the golden ratio.

Indeed, let \( N_h \) be the fewest nodes of an AVL tree of height \( h \): the root of such a tree has a subtree of height \( h - 1 \), and the other, at least \( h - 2 \) high by the balance, is as small as possible; hence \( N_h = N_{h-1} + N_{h-2} + 1 \) with \( N_0 = 1 \) and \( N_1 = 2 \), i.e., \( N_h + 1 = F_{h+3} \); since \( F_k > \varphi^k / \sqrt{5} - 1 \) (\( F_k \) is the integer nearest to \( \varphi^k / \sqrt{5} \)), \( n + 1 \ge F_{h+3} \) gives \( \varphi^{h+3} < \sqrt{5} ( n + 2 ) \), i.e., (2). An insertion changes by 1 the heights on its path, and the lowest node left unbalanced, with a difference of 2, is rebalanced by a single rotation, if the higher grandchild is on the outside, or by a double one, which restores the height that the subtree had before the insertion, so that nothing above changes; a removal may shorten the subtree it rebalances, and the rotations may go on up to the root.

A treap (Seidel and Aragon) gives each key a random priority and keeps the tree a binary search tree on the keys and a heap on the priorities, the root of each subtree of the highest priority in it. Its shape is then unique, that of the binary search tree built by inserting the keys by decreasing priority, i.e., in a random order, whatever the order of the operations: the expected depth of a node is \( O( \log n ) \), as for a random insertion order. A new key is inserted at a leaf and rotated up while its priority beats its parent's, and each rotation adds one node to the right spine of its left subtree or to the left spine of its right subtree; the rotations are therefore the lengths of those two spines at the end, whose expectation is less than 2 (Seidel and Aragon), and a removal makes the same rotations in reverse.

A splay tree (Sleator and Tarjan) keeps no balance at all: each access moves the node accessed to the root by rotations in pairs, a zig-zig when the node and its parent are both left (or right) children, two rotations from the top, and a zig-zag otherwise; the top-down splay does the same in one pass from the root, setting aside the keys met into a left and a right tree.

Lemma 3 (the access lemma, Sleator and Tarjan). Let each node \( x \) have a weight \( w( x ) > 0 \), \( s( x ) \) the total weight of its subtree and \( r( x ) = \log_2 s( x ) \) its rank, and let the potential be \( \Phi = \sum_x r( x ) \). The splay of a node \( x \) in a tree of root \( t \) costs, amortized,

\[ 1 + 3 ( r( t ) - r( x ) ) = O\Bigl( \log \frac{ s( t ) }{ w( x ) } \Bigr) . \tag{3} \]

Indeed, a zig-zig or a zig-zag step that lifts \( x \) by two levels changes \( \Phi \) only on the three nodes it rotates, and the concavity of the logarithm bounds its two rotations plus that change by \( 3 ( r'( x ) - r( x ) ) \), \( r' \) the rank after the step; the last single rotation, if any, adds 1 more. The terms telescope along the path to \( 3 ( r( t ) - r( x ) ) + 1 \). With the weights all 1, \( r( t ) = \log_2 n \) and (3) is \( O( \log n ) \); since \( \Phi \le n \log_2 n \) at the start and \( \Phi \ge 0 \), a sequence of \( m \) operations costs \( O( ( m + n ) \log n ) \). With the weights the frequencies of the accesses, (3) gives the static optimality, i.e., a cost within a constant factor of the best static tree for those frequencies, with no knowledge of them.

Join-based algorithms

The balanced trees above restore their balance inside each insertion and each removal. Blelloch, Ferizovic and Sun showed that one operation suffices instead, the join: \( \mathrm{join}( L , k , R ) \), for two balanced trees \( L \) and \( R \) whose keys are smaller and larger than \( k \), returns a balanced tree of all the keys, and every other operation (split, insertion, removal, union, intersection, difference, batches, filters) is written on join alone, once for all the schemes (JoinAlgorithms.h). The cost of join is bounded through a rank \( r( T ) = \Theta( \log n ) \): the height for the AVL trees, the black height for the Red-Black trees, \( \log_2 \) of the weight (the keys plus 1) for the trees balanced by weight, and the height in expectation for the treaps.

Lemma 4 (the join). For each of the four schemes, \( \mathrm{join}( L , k , R ) \) costs \( O( | r( L ) - r( R ) | + 1 ) \) for the first three, and \( O( \log n ) \) in expectation for the treaps, whose join merges two spines; the rank of its result is between \( \max( r( L ) , r( R ) ) \) and that plus 1 (in expectation for the treaps).

Indeed, if \( L \) is higher, the join goes down the right spine of \( L \) until it meets a subtree \( c \) of the rank of \( R \), makes the node \( ( c , k , R ) \) there, and fixes the balance on the way back by at most a double rotation per level. For the AVL trees the subtree met has height \( h( R ) \) or \( h( R ) + 1 \), the new node at most \( h( R ) + 2 \), and a single or a double rotation at the parent brings the difference back to 1; for the Red-Black trees the subtree met is black, of the black height of \( R \), the new node is red, and the only fault, a red node with a red child, climbs by one rotation per level and is solved at the root by painting it black; for the trees balanced by weight, with the parameter \( \alpha \le 1 - 1 / \sqrt{2} \), each level needs a single or a double rotation; for the treaps, join merges the two spines by the priorities, and \( k \) goes down until its priority beats those below, as an insertion does. The levels of the spine walked are \( | r( L ) - r( R ) | + O( 1 ) \).

A split of \( T \) at \( k \) exposes the root \( ( L , m , R ) \), recurs on the side of \( k \), and joins the other side with \( m \) and the part of the recursion on its side. The trees joined at the successive levels of the path have ranks that grow by the ranks of the subtrees left behind, so that by Lemma 4 the costs of the joins telescope to \( O( r( T ) ) = O( \log n ) \); join2, the join with no key in between, takes the largest key of \( L \) off it and joins it with \( R \), again in \( O( \log n ) \), and the insertion and the removal are a descent followed by joins on the way back.

Lemma 5 (the work of the set operations, Blelloch, Ferizovic and Sun). The union, the intersection and the difference of two trees of sizes \( m \le n \), by expose, split and join, take the work

\[ W( m , n ) = \Theta\Bigl( m \log\Bigl( \frac{n}{m} + 1 \Bigr) \Bigr) , \tag{4} \]

which is optimal among the algorithms by comparisons, and, with the two recursive calls in parallel, the span \( O( \log m \log n ) \).

The union exposes the root \( ( L , k , R ) \) of the smaller tree, splits the larger at \( k \), takes the unions of the two left and of the two right sides, and joins them with \( k \); the intersection and the difference differ only in whether \( k \) survives, and use join2 when it does not. At the level \( i \) of the recursion the smaller tree has been cut into at most \( 2^i \) pieces, and the larger into at most \( 2^i \) pieces of sizes \( n_j \) summing to \( n \); their splits cost \( \sum_j \log( n_j + 1 ) \le 2^i \log( n / 2^i + 1 ) \) by the concavity of the logarithm. Summed over the \( \log_2 m \) levels, and with the joins costing no more than the splits (their rank differences telescope as in the split), this gives (4), which matches the lower bound \( \log_2 \binom{m + n}{m} \) of the comparisons needed to merge two sorted sequences (Hwang and Lin; Brown and Tarjan): it is \( \Theta( m + n ) \) for \( m \approx n \) and \( \Theta( \log n ) \) for \( m = 1 \). The two recursive calls touch disjoint trees, and each level waits for one split and one join, whence the span. A sorted batch of \( m \) pairs is inserted (or removed) as the union (or the difference) with the tree that the batch would make, without building it, the batch being split by a binary search on the key of the root, in the same work; a filter and a map-reduce visit every node, in \( O( n ) \) work.

Augmented maps

A node may keep, besides its size, a value of its subtree computed from those of its children and of its own pair, e.g., the sum or the maximum of the values; since every node that changes is rebuilt by \( \mathrm{node}( L , k , R ) \), which recomputes it, and a rotation is two such rebuilds, join keeps it, and so does every operation above (JoinTree.h). An augmented map (Sun, Ferizovic and Blelloch) takes a monoid \( ( A , \otimes , e ) \) and a map \( g \) of a pair into \( A \), and each node \( u \) keeps

\[ \mathit{aug}( u ) = \mathit{aug}( u.\mathit{left} ) \otimes g( u.k , u.v ) \otimes \mathit{aug}( u.\mathit{right} ) , \tag{5} \]

the combination of the values of its pairs in the order of the keys, which needs no commutativity. The augmented value of the keys in a range \( [ \mathit{lo} , \mathit{hi} ] \) is the combination of \( O( \log n ) \) pieces: from the node where the paths to \( \mathit{lo} \) and to \( \mathit{hi} \) part, the pairs of the path to \( \mathit{lo} \) not below \( \mathit{lo} \) with the right subtrees they leave behind, the pair of the node, and symmetrically on the path to \( \mathit{hi} \), at most two pieces per level of a balanced tree; the interval trees and the range trees of the library are augmented maps of this kind (see Stabbing and range counting on augmented maps).

B-trees

A B-tree of minimum degree \( t \ge 2 \) (Bayer and McCreight) is a search tree whose nodes hold several keys in increasing order: a node of \( j \) keys \( k_0 < \cdots < k_{j-1} \) that is not a leaf has \( j + 1 \) children, the child \( c_i \) holding the keys between \( k_{i-1} \) and \( k_i \), and the tree keeps the invariants

\[ t - 1 \le j \le 2 t - 1 \text{ (the root: } 1 \le j \le 2 t - 1 \text{)} , \qquad \text{all the leaves at the same depth} . \tag{6} \]

The keys of a node are read in one transfer from the secondary memory, a node filling a block, so that the measure of the cost is the number of the nodes read, the I/Os of the model of the two-level memory (Aggarwal and Vitter), rather than the comparisons, which a node of many keys answers in the main memory.

Lemma 6 (the height of a B-tree). A B-tree of minimum degree \( t \) with \( n \ge 1 \) keys has height

\[ h \le \log_t \frac{ n + 1 }{ 2 } , \tag{7} \]

and a search reads \( h + 1 = O( \log_t n ) \) nodes, with \( O( \log t ) \) comparisons in each, by a binary search, i.e., \( O( \log n ) \) in all.

Indeed, by (6) the root has at least 2 children, and every other node that is not a leaf at least \( t \); hence there are at least \( 2 t^{d-1} \) nodes at the depth \( d \ge 1 \), each with at least \( t - 1 \) keys, and

\[ n \ge 1 + ( t - 1 ) \sum_{d=1}^{h} 2 t^{d-1} = 2 t^h - 1 , \]

which gives (7). The search goes down one path, from the root to a leaf at most, and in each node it finds the place of the key among at most \( 2 t - 1 \) keys. With \( t \) of the order of the keys of a block, e.g., \( t = 128 \), three levels index millions of keys, and the root and the level below it stay in the main memory.

The insertion and the removal keep (6) with two operations on a node and its parent. A split of a full node \( y \) of \( 2 t - 1 \) keys, the child \( c_i \) of \( x \), moves its median key into \( x \) at the place \( i \) and its last \( t - 1 \) keys, with their children, into a new node, the child \( c_{i+1} \) of \( x \): both halves have \( t - 1 \) keys, and \( x \) one key more. A merge is its converse: two siblings of \( t - 1 \) keys each and the key of their parent between them become one node of \( 2 t - 1 \) keys; a borrowing moves the key of the parent down into a node and a key of a sibling with at least \( t \) keys up in its place, which keeps the order of the keys.

Lemma 7 (the operations in one pass). insert() and remove() of BTree.h keep (6), each in one pass from the root down, with \( O( \log_t n ) \) splits, merges or borrowings of \( O( t ) \) each, i.e., \( O( t \log_t n ) \) time and \( O( \log_t n ) \) I/Os.

Indeed, the insertion splits every full node it is about to enter, so that the parent of a full node always has room for the median; a full root splits under a new root, which is the only way the height grows, and keeps all the leaves at the same depth. The key goes into the leaf reached, which is not full. The removal enters only nodes with at least \( t \) keys (the root apart): before going down into a child of \( t - 1 \) keys it borrows a key from a sibling of \( t \) keys or more, or merges it with a sibling of \( t - 1 \), so that a key can always leave the node entered without breaking (6). A key found in an internal node is replaced by its predecessor, or by its successor, which lie in a leaf below a child with at least \( t \) keys, and is then removed from that leaf; if both children have \( t - 1 \) keys, they are merged around it, and it goes down with them. A root left with no key gives way to its only child, which is the only way the height falls. A replacement by the predecessor or by the successor walks down to its leaf and then down again from the node it left, so that the removal reads at most \( 2 ( h + 1 ) \) nodes.

The B+-tree of section 6.3 of the book (BPlusTree.h) keeps the values in the leaves alone, the internal nodes holding the bounds of their children, i.e., the largest key below each child but the last, so that an internal node of a block holds more children and the tree is lower; the leaves are linked in a list in the order of the keys, and the \( k \) pairs of an interval are read in \( O( \log n + k ) \) time, by a search of its smallest key and a walk along the leaves, \( O( \log_t n + k / t ) \) I/Os when the leaves fill blocks. BTreeMap.h is a B+-tree in the main memory, where a node is a few lines of cache rather than a block: the place of a key is counted on all the places of a node at once, by comparisons of vectors on padded nodes, the lines of the next node are prefetched on the way down (Chen, Gibbons and Mowry), and the splits on the edges of the tree keep the old node full when the keys arrive in order, so that a sorted sequence fills all the nodes; with the counts of the pairs below each child it answers rank() and select() along one path, as the order-statistic trees do.

The B-trees of the area and the cost of their operations, for \( n \) keys, \( t \) the minimum degree, \( m \) the order and \( k \) the pairs of an interval
HeaderValuesSearch, insertionRemovalIntervalMemory
BTree.hin every node\( O( t \log_t n ) \)\( O( t \log_t n ) \)\( O( t \log_t n + k ) \), by the iteratorsecondary, a node a block
BPlusTree.hin the leaves, linked\( O( m \log_m n ) \)\( O( m \log_m n ) \), exercise 14.8 of Morin\( O( m \log_m n + k ) \)secondary, a node a page
BTreeMap.hin the leaves, linked\( O( ( L + I ) \log n ) \)\( O( ( L + I ) \log n ) \)\( O( ( L + I ) \log n + k ) \)main, a node a few lines of cache

The B+-tree of BPlusTree.h also removes (exercise 14.8 of Morin's book): a leaf left with fewer than \( \lceil m / 2 \rceil \) keys takes the nearest key of a sibling that has more, through their separator, which becomes the largest key of the left one, or is merged with it, the parent losing the separator and a child; an internal node left with fewer than \( \lceil m / 2 \rceil \) children rotates a child through the separator, or is merged with a sibling and the separator between them. A separator bounds the keys on its two sides and need not be a key still there, so that a removal changes only the separators of its borrows and merges, and the keys of the B-tree above the leaves are at most one per leaf, a share \( 1 / \lceil m / 2 \rceil \) of the keys that vanishes as \( m \) grows. findRange( x , y ), the keys in \( ( x , y ] \), goes down to the leaf of \( x \) and along the list, \( O( \log_m n + k ) \) nodes for \( k \) keys.

Dynamic trees

Beyond the book, the link-cut trees of Sleator and Tarjan (LinkCutTree.h) keep a forest of rooted trees that changes by the insertion of an edge between two trees (link()) and by the removal of an edge (cut()), and answer on it whether two nodes are in the same tree, the root of a tree, the lowest common ancestor of two nodes and the aggregate of the values on the path between two nodes, all in \( O( \log n ) \) amortized time; a forest kept as a vector of parents answers the same in time proportional to the depth, and one kept as the jumps of the binary lifting answers in \( O( \log n ) \) but must be built again, in \( O( n \log n ) \), at each change of its shape. Each node marks at most one of its children as preferred, so that the forest is split into preferred paths; each path is kept by a splay tree whose order is that of the depths, its leftmost node the shallowest, and the root of that splay tree points to the parent of the top of the path (a path-parent pointer, which no child pointer matches). The operation \( \mathrm{access}( v ) \) splays \( v \) in its splay tree, drops the deeper part of its path, and then climbs: at each path-parent \( x \) it splays \( x \) and makes the path below it the one just built, until the path from the root of the tree to \( v \) is a single splay tree with \( v \) at its root. The other operations are one or two accesses and a few pointers: evert( v ) reverses the path from the root to \( v \) after its access, by a flag pushed down lazily, which makes \( v \) the root; link( u , v ) everts \( u \) and hangs it under \( v \); cut( u , v ) everts \( u \) and accesses \( v \), which leaves \( u \) alone as the left child of \( v \); the aggregate of the path between \( u \) and \( v \) is the one kept at the root after evert( u ) and access( v ), which is why the operation of the aggregates must be commutative.

Lemma 8 (the cost of an access, Sleator and Tarjan). With the weight of each node the number of its descendants in the forest plus 1, i.e., with the ranks of (3) on the virtual tree made of the splay trees and of the path-parent pointers, and \( k \) the number of preferred paths that \( \mathrm{access}( v ) \) enters, the access costs, amortized,

\[ O( \log n ) + k , \qquad \text{and} \qquad \sum k = O( ( m + n ) \log n ) \tag{8} \]

over any sequence of \( m \) operations.

Indeed, the splays of an access telescope by (3) along the virtual tree, since the rank of the root of a splay tree is at most that of its path-parent, to \( 3 \log_2 n + O( k ) \); the \( k \) changes of the preferred child are bounded by the heavy-light argument, i.e., a change that makes a light child preferred happens at most \( \log_2 n \) times per access (a light child has at most half the descendants of its parent), and one that makes a heavy child preferred is paid by an earlier change of the other kind or by a link or a cut, each of which turns at most \( \log_2 n \) edges from heavy to light. The extra rotations of the \( k \) climbs are absorbed by doubling the constant of (3); hence every operation costs \( O( \log n ) \) amortized, and a sequence of \( m \) of them \( O( ( m + n ) \log n ) \).

The weights of the edges are kept on nodes of their own, one in the middle of each edge, so that the maximum on the path between \( u \) and \( v \) is that of the values of the nodes; this is how the minimum spanning forest of Reoptimization.h finds, in \( O( \log n ) \) amortized time, the heaviest edge of the cycle that a new edge closes, and swaps the two (see Changes of the graph and reoptimization). The experiments of Tarjan and Werneck rank the link-cut trees first among the dynamic trees when the operations are mostly links, cuts and queries on paths, the topology trees and the top trees being preferable for queries on subtrees. On shallow trees, however, they find the plain vector of the parents the fastest of all, an evert being the reversal of a short path: so LinkCutTree starts as that vector, keeps the path of its last walk from a node for an evert of that node that follows (no load of a parent then waits for the one before), and counts the steps of its walks (those of its preconditions apart, so that the level of the contracts changes nothing); once their recent mean exceeds a bound, about where the constant of the splay trees is paid back, it turns into splay trees in \( O( n ) \), every node a splay tree of its own whose path-parent is its parent, and stays so. The costs of the operations are then \( O( d ) \) for a depth \( d \) below the bound and \( O( \log n ) \) amortized after it.

The trees of Open Data Structures

The binary trees, the random binary search trees, the scapegoat trees and the red-black trees of chapters 6 to 9 of Morin, Open Data Structures, are in the area with every exercise of those chapters that asks for code: the traversals and the measures of chapter 6 in BinaryTreeAlgorithms.h and MeasuredSearchTree.h, the treaps of chapter 7 in Treap.h, HashedTreap.h and FingerTreap.h, with RandomizedSearchTree.h and, in the area of the sequences, TreapList.h, the trees of chapter 8 in ScapegoatTree.h and PartialRebuildingTree.h (see Trees of partial rebuilding), and the tree of chapter 9 in LeftLeaningRedBlackTree.h (see Left-leaning red-black trees). The exercises that ask for a proof or an answer are answered here, in the order of the book; those that ask to illustrate an operation on a figure of the book are not reproduced, the operations being tested on random sequences instead.

The binary trees (chapter 6). A tree of \( n \ge 1 \) nodes has \( n - 1 \) edges, one from each node but the root to its parent (exercise 6.1), and \( n + 1 \) external nodes, since each of the \( n \) nodes has two child places and \( n - 1 \) of them hold nodes (exercise 6.2); if a tree has a leaf and its root has two children, each subtree of the root holds a leaf, hence there are two (exercise 6.3). The functions nextPreorder(), nextInorder() and nextPostorder() find the next node by the links to the parents (exercise 6.8): over a whole visit each edge is walked down once and up once, so that \( n \) calls cost \( O( n ) \) although one call may cost \( \Theta( h ) \); subtreeSize() and subtreeHeight() walk a subtree in the same way, entering each node from its parent, from its left child and from its right child, and knowing which one from the node they leave (exercises 6.4 and 6.5). The test of the balance of the sizes (exercise 6.6) returns the size of each subtree from the postvisit, so that each node is examined once, where a test that calls size() at each node costs \( \Theta( n h ) \).

Lemma 9 (the three numbers, exercises 6.7 and 6.9). Let \( \mathrm{pre}( u ) \), \( \mathrm{in}( u ) \) and \( \mathrm{post}( u ) \) be the numbers of \( u \) in the three visits, \( d( u ) \) its depth and \( n_u \) the size of its subtree. Then \( u \) is an ancestor of \( w \) if and only if \( \mathrm{pre}( u ) \le \mathrm{pre}( w ) \) and \( \mathrm{post}( w ) \le \mathrm{post}( u ) \), and

\[ \mathrm{post}( u ) - \mathrm{pre}( u ) = n_u - 1 - d( u ) ; \tag{9} \]

the three numbers of a node do not determine \( n_u \) nor \( d( u ) \).

Indeed, the previsit lists the subtree of \( u \) as an interval that starts at \( u \), and the postvisit as an interval that ends at \( u \), which gives the test of the ancestors. Let \( L \) be the nodes that precede \( u \) in both visits, those of the subtrees hanging to the left of the path to \( u \): the previsit puts before \( u \) the \( d( u ) \) ancestors and \( L \), the postvisit puts \( L \) and the \( n_u - 1 \) descendants, whence (9). The tree of the five nodes 0 to 4 along a path of right children and the tree whose root 0 has the leaf 1 on the left and 2 on the right, 2 with a right leaf 3, give the node 2 the numbers \( ( 2 , 2 , 2 ) \) in both, with \( n_u = 3 \) and \( d( u ) = 2 \) in the first, 2 and 1 in the second (the test of exercise 6.7 builds the two); hence the size and the depth need a number more, e.g., the size kept in the node. The previsit and the invisit together determine the tree (exercise 6.10, by fromPreorderInorder(), Lemma 1): the first node of the previsit is the root and splits the invisit into the two subtrees, recursively.

The shape of a tree of \( n \ge 1 \) nodes fits in \( 2 ( n - 1 ) \) bits (exercise 6.11): shapeCode() writes, in the previsit, whether each node has a left and a right child, and drops the two bits of the last node, which is a leaf; fromShapeCode() reads them back by a stack of the nodes whose right child is due. There are \( C_n = \binom{2n}{n} / ( n + 1 ) \) shapes, the Catalan numbers, and \( \log_2 C_n = 2 n - \frac32 \log_2 n + O( 1 ) \), so that the code exceeds the least one by \( O( \log n ) \) bits.

The keys \( 1 , \ldots , n \) make a binary search tree of height \( n - 1 \) when every key inserted after the first is the smallest or the largest of those left, i.e., when the first key is \( 1 \) or \( n \) and so on recursively: \( 2^{n-1} \) of the \( n! \) orders (exercise 6.15, counted for \( n \le 7 \) by the test of exercise 6.19). An add(x) followed by remove(x) gives the tree back when \( x \) was absent, since the node of \( x \) is then a leaf, which the removal unlinks, and not when \( x \) was there, since the removal takes the key away (exercise 6.16). A removal never raises a node: the splice of a node with one child lifts that subtree by one level and leaves the rest where it was, so that the heights decrease or stay (exercise 6.17); an insertion adds one leaf, which raises the heights of its ancestors by 1 at most and that of the tree by 1 at most (exercise 6.18). The getLE of exercise 6.14 goes down the path of \( x \) and visits whole every left subtree that hangs from a node not larger than \( x \), \( O( n' + h ) \); and MeasuredSearchTree keeps the size, the depth and the height of each node (exercise 6.19), removing always a leaf so that no depth changes (see its header).

The random binary search trees (chapter 7). Let \( f( h ) \) be the number of orders of insertion of \( 2^{h+1} - 1 \) keys that build the complete tree of height \( h \): the middle key comes first, and the two halves, \( 2^h - 1 \) keys each, interleave in any of \( \binom{2^{h+1} - 2}{2^h - 1} \) ways, each in one of its \( f( h - 1 ) \) orders, so that

\[ f( h ) = \binom{2^{h+1} - 2}{2^h - 1} f( h - 1 )^2 , \quad f( 0 ) = 1 , \tag{10} \]

\( f( 1 ) = 2 \), \( f( 2 ) = 20 \cdot 4 = 80 \) and \( f( 3 ) = 3432 \cdot 6400 = 21964800 \) (exercise 7.3, checked by the test, which counts the 80 orders of 7 keys). shuffleFast() [see RandomGenerators.h] is the uniform shuffle of exercise 7.4 (Lemma 15 of Sequences by rank and order maintenance). An insertion into a treap makes \( O( 1 ) \) rotations in expectation (exercise 7.5): each rotation that lifts the new node adds a node to the right spine of its left subtree or to the left spine of its right one, and the node \( y < x \) lies on the right spine of the left subtree of \( x \) exactly when \( x \) and \( y \) have the larger priorities of the keys from \( y \) to \( x \) and \( y \) the second one, probability \( \frac{1}{k ( k + 1 )} \) for \( k \) the difference of their ranks (the two parts of Lemma 7.2 of Morin, on the treap as a random tree); summed over \( k \), each spine has less than one node in expectation, and the removal reverses the insertion.

A rotation at \( u \) changes the subtrees of the two nodes it turns, and their sizes and heights follow from those of their children in \( O( 1 ) \), the lower one first (exercise 7.7); the depths do not: a rotation moves a whole subtree one level up or down, and all its depths change. The treap of sorted keys is built in \( O( n ) \) by the stack of the right spine (exercise 7.8, Treap::fromSorted()): each key is pushed once and popped once, and the priorities, drawn in the order of the keys, are those that the insertions in that order would draw, so that the tree is the same. The finger search of exercise 7.9 and the treap whose priorities are hashes of the addresses (exercise 7.6) are discussed in their headers, FingerTreap.h and HashedTreap.h; the access by rank of exercise 7.10 is select(), the list of exercise 7.11 TreapList, and the split and the absorb of exercises 7.12 and 7.13 the split() and the join2() of Treap (see Join-based algorithms). The randomized search trees of Martínez and Roura (exercise 7.14) make at each node of an insertion the choice that a treap makes by the priorities, the new key at the root of a subtree of \( m \) keys with probability \( 1 / ( m + 1 ) \), and in a removal the root of the join of two subtrees of sizes \( a \) and \( b \) from the first with probability \( a / ( a + b ) \); both are the probabilities that the largest of the priorities fall where the treap would put it, so that the two trees have the same distribution of shapes, the test checking it on the paths of 5 keys, of probability \( 2^4 / 5! \).

The scapegoat trees (chapter 8). Let \( 1 < b < 2 \) and keep \( q / 2 \le n \le q \) and every depth at most \( \log_b q \).

Lemma 10 (the scapegoat). If a leaf \( u \) has the depth \( d > \log_b q \), an ancestor \( w \) of \( u \) has \( b^{d - d( w )} > n_w \), and the deepest one has a child \( c \) on the path with \( n_c > n_w / b \); rebuilding its subtree perfectly balanced leaves every node at depth at most \( d - 1 \).

Indeed, the root qualifies, since \( b^d > q \ge n \), and the leaf does not, since \( b^0 = n_u \). If \( w \) is the deepest that qualifies and its child \( c \) on the path had \( n_c \le n_w / b \), then \( n_c < b^{d - d( w ) - 1} = b^{d - d( c )} \), i.e., \( c \) would qualify too, against the choice of \( w \). The perfectly balanced tree of \( n_w \) nodes has height \( \lfloor \log_2 n_w \rfloor \le \log_b n_w < d - d( w ) \), i.e., at most \( d - d( w ) - 1 \), and the parent of \( u \) was at depth \( d - 1 \le \log_b ( q - 1 ) \) before the insertion.

The rule of Morin takes instead the first ancestor with a child too large (Scapegoats::WEIGHT), and his argument that its subtree is not complete and loses a level needs a step that he leaves unstated: before the insertion the tree was at most \( \log_b ( q - 1 ) < d \) high, so that the new leaf is the only node at the depth \( d \); a subtree of height \( H \) with one node at its last level has at most \( 2^H \) nodes, and exactly \( 2^H \) only when its other levels are complete, which leaves no child with more than half of it, so that the subtree of the scapegoat has fewer than \( 2^H \) nodes and its rebuild loses a level (see ScapegoatTree.h); the class keeps his rule as an option, checked by the invariant. The cost is that of Lemma 8.3 of Morin with \( b \) for \( 3 / 2 \): after a rebuild of \( w \) its two children differ by one node at most, and before the next rebuild of \( w \) one of them must hold more than \( n_w / b \) of them, i.e., at least \( ( 1 / b - 1 / 2 ) n_w \) insertions and removals must pass through \( w \); giving each node of the path of an operation \( c = 1 / ( 1 / b - 1 / 2 ) = 2 b / ( 2 - b ) \) credits pays the rebuild, and the removals pay the rebuild of the whole tree at \( q > 2 n \) with one credit each. Hence the amortized cost of an insertion or a removal is \( O( \frac{b}{2 - b} \log_b n ) \) and that of a search \( O( \log_b n ) \) in the worst case (exercise 8.4): the searches get faster as \( b \) grows to 2 and the updates slower, without bound, which the test of exercise 8.4 sees in the work of the rebuilds.

The insertions of \( 1 , \ldots , n \) make rebuilds of \( \Omega( n \log n ) \) nodes in all (exercise 8.3), which is proved for the rule of Morin with \( \sqrt{2} < b < 2 \): each key is added at the end of the right spine, whose length is at least \( \log_2 ( t + 1 ) - 1 \) after \( t \) insertions, so that a key starts below that many nodes of the spine, and ends below at most \( \log_b n - \log_2 ( n - x + 2 ) + 2 \) of them; a rebuild of \( s \) nodes takes at most \( s \, b / ( b - 1 ) \) of these nodes away, since the sizes shrink by \( b \) below the scapegoat, and the sum gives at least \( \frac{b - 1}{b} ( ( 2 - 1 / \log_2 b ) n \log_2 n - 3.9 n ) \) nodes rebuilt. For the rule of Galperin and Rivest, and for \( b \le \sqrt{2} \), it is measured, not proved: the test measures \( \Theta( n \log n ) \) with a ratio within a factor 2 for \( n \) from \( 2^8 \) to \( 2^{12} \). The sizes recomputed at each step cost \( \sum_i n_{u_i} \) along the climb, at most \( b / ( b - 1 ) \cdot n_w \) by the growth of the sizes below the scapegoat (exercise 8.5 reduces it to \( n_w \), counting only the other child of each node), and the sizes stored in the nodes cost one addition per level of every update instead (exercise 8.6); the rebuild by a list (exercise 8.7) threads the subtree by its right links in symmetric order, the left spine by a loop and the right subtrees by recursion, and builds the tree of the first \( s \) nodes as the tree of the first \( \lfloor ( s - 1 ) / 2 \rfloor \), the next node and the tree of the rest, advancing along the list, \( O( s ) \) time with no buffer and a recursion of \( O( \log s ) \) for the building.

Trees of partial rebuilding

The trees of exercises 8.8 to 8.10 of Morin (PartialRebuildingTree.h) are binary search trees that keep the size of each subtree and, after an insertion or a removal, rebuild perfectly balanced the subtree of the highest node of the path that a rule selects. A rebuild of \( s \) nodes costs \( O( s ) \) and leaves the two children of each of its nodes with \( \lfloor ( s - 1 ) / 2 \rfloor \) and \( \lceil ( s - 1 ) / 2 \rceil \) nodes. In each case the rule must keep the children of every node within a constant fraction \( \beta < 1 \) of its subtree, so that the height is \( \log_{1/\beta} n \), and must let \( \Omega( s ) \) operations pass through a node between two of its rebuilds, so that the rebuilds cost \( O( 1 ) \) per operation and per node of its path.

Lemma 11 (the drift of a balanced subtree). Let a node be rebuilt with \( s \) nodes, and let \( k \) operations pass through it after, \( i \) insertions and \( r \) removals. Then each of its children holds at most \( \frac34 \) of its subtree if \( k \le s / 3 \), and at most \( \frac23 \) of it if \( k \le s / 4 \).

Indeed, a child holds at most \( s / 2 + i \) nodes and the subtree at least \( s + i - r \); the ratio is at most \( \beta \) as long as \( s / 2 + i \le \beta ( s + i - r ) \), which for \( \beta = \frac34 \) reads \( i + 3 r \le s \) and holds when \( 3 k \le s \), and for \( \beta = \frac23 \) reads \( i + 4 r \le s \), which holds when \( 4 k \le s \).

For WeightRebuildTree (exercise 8.8) the rule is the invariant itself, every child at most \( \frac23 \) of its parent's subtree: the height is at most \( \log_{3/2} n \), and by Lemma 11 at least \( s / 4 \) operations pass through a node between its rebuilds, hence \( O( \log n ) \) amortized time; a removal can break the invariant only at a child out of its path, which shrinks relatively, and the rule checks both children of each node of the path. For CountdownTree (exercise 8.9) the timer of a node rebuilt with \( s \) nodes is \( \lfloor s / 3 \rfloor \): at most \( s / 3 \) operations pass through it before its next rebuild, hence by Lemma 11 its children stay within \( \frac34 \) of it and the height is at most \( \log_{4/3} n + O( 1 ) \) (the subtrees of fewer than 3 nodes, whose timer is 0, are rebuilt by the next operation, at a constant cost); the rebuild costs \( O( s ) \), paid by the \( s / 3 \) operations that ran its timer out, and the nodes rebuilt with an ancestor start their timers again with the new sizes. For DynamiteTree (exercise 8.10) a node of size \( s \) on the path explodes with probability \( 1 / s \), at a cost \( s \), i.e., \( O( 1 ) \) expected per node and per operation. On a sequence of insertions fixed in advance, a node rebuilt with \( s \) nodes goes past \( \frac34 \) only after \( k > s \) insertions through it, and it survives them with probability \( \prod_{t=1}^{k} ( 1 - 1 / ( s + t ) ) = s / ( s + k ) < 1 / 2 \); with no removal, the keys of the subtree at each depth of the path of a key, and the key of its root, depend only on the draws of that depth and of those above, so that the bound holds for each edge of the path given the edges above it, and the path has at most \( 2 \lfloor \log_{4/3} n \rfloor + 2 \) nodes in expectation, an operation costing \( O( \log n ) \) expected time. A removal that splices out a node lifts its subtree by one level, built by the draws of the level below, and with removals no bound on the depth is proved.

The order maintenance of exercise 8.11 is in the area of the sequences (OrderMaintenanceList.h): labels that encode the paths of a tree change for a whole subtree at each rotation and are rewritten for free by the rebuild of a scapegoat tree, the case where Morin remarks that the partial rebuilding is the right choice, in \( O( \log n ) \) amortized; the library takes instead the list labeling of Bender et al., which needs no tree and costs \( O( 1 ) \) amortized (see Sequences by rank and order maintenance).

Left-leaning red-black trees

A 2-4 tree has all its leaves at the same depth and every internal node with 2 to 4 children; with \( n \) keys it has \( n + 1 \) leaves, and its height \( h \) satisfies \( 2^h \le n + 1 \) (Lemma 9.1 of Morin). BTree of minimum degree 2 [see BTree.h] is a 2-4 tree. The RedBlackTree of Morin, LeftLeaningRedBlackTree here, stores it in a binary tree: a node of degree \( k \) is a black node with \( k - 2 \) red children, the red one on the left for \( k = 3 \), and the black height is the height of the 2-4 tree (exercise 9.1 asks for this correspondence on a figure; twoFourDegrees() counts the nodes of each degree).

Lemma 12 (the counts of a 2-4 tree, exercise 9.8). A 2-4 tree with \( n_\ell \) leaves has \( ( n_\ell - 1 ) / 3 \le n_i \le n_\ell - 1 \) internal nodes, and the red-black tree of it has \( n_3 + 2 n_4 = n - n_i \) red nodes, \( n_k \) the internal nodes of degree \( k \) and \( n = n_\ell - 1 \) the keys.

Indeed, a node of degree \( k \) holds \( k - 1 \) keys, so that \( n = n_2 + 2 n_3 + 3 n_4 \), between \( n_i \) and \( 3 n_i \); the black nodes are the \( n_i \) internal nodes and the others are red. The bounds are reached by the trees of degree 2 only and of degree 4 only; the test checks the identity and the bounds at each step of a random sequence.

Red-black trees of height \( 2 \log_2 n - O( 1 ) \) exist (exercise 9.4), and sequences of operations build them (exercise 9.6): the insertions of \( n , n - 1 , \ldots , 1 \) in decreasing order build in LeftLeaningRedBlackTree a tree of height exactly \( 2 \log_2 n - 3 \) for \( n = 2^k \), \( k \ge 3 \), and at least \( 2 \log_2 ( n + 3 ) - 2 \log_2 3 - 2 \) for every \( n \): the left spine of the 2-4 tree is a counter whose digits, the keys of its nodes, are 2 or 3 below the root, so that each of its nodes but possibly the root adds a red node to the leftmost path (the test checks it for \( 6 \le k \le 12 \)). The other sequences measured, the insertions in increasing order and random insertions and removals, stayed no higher for \( n \ge 256 \). pushBlack() splits a 2-4 node of degree 5 into two of degree 2 and 3 and sends a key to the parent, pullBlack() merges two 2-4 nodes and the key between them into one (exercise 9.5). The removal sets the parent of the spliced child since the child may be the sentinel nil, whose parent the splice does not write and removeFixup() reads (exercise 9.7); here a node of no key stands for the nil for the time of removeFixup().

A binary search tree of height at most \( 2 \log_2 n - 2 \) cannot always be colored (exercise 9.9): let the root have a leaf on the left and a complete tree of height \( H \ge 4 \) on the right, so that \( n = 2^{H+1} + 1 \) and the height \( H + 1 \le 2 \log_2 n - 2 \); the path through the leaf has at most 2 black nodes, while a path of \( H + 2 \) nodes with no two red ones in a row has at least \( ( H + 2 ) / 2 \ge 3 \), so that no coloring gives the same black height to both. When a coloring exists the left-leaning property may still fail: a node with a right child and no left one needs that child red, since its nil on the left has no black node below it, and a red right child under a black left nil breaks the property; the complete tree of 7 nodes with one more key below its largest leaf is colorable, of height \( 3 \le 2 \log_2 8 - 2 \), and not left-leaning. Two red-black trees whose keys are separated join in \( O( |h_1 - h_2| + \log n ) \) (exercises 9.10 and 9.11, absorb()): the smallest key of the second becomes a red node over the second tree and the subtree of the right spine of the first with the same black height, which keeps the black heights, and addFixup() restores the other two properties going up.

For the AVL trees (exercises 9.12 and 9.13, AVLTree.h), an insertion rebalances once at most: the lowest unbalanced node gets back, by one or two rotations, the height it had before the insertion, so that nothing above changes. A removal from the tree of Fibonacci of height \( h \) (the smallest AVL tree of that height, see (2)) of the deepest leaf on the side of the shorter subtrees makes every node of its path unbalanced in turn, \( \Theta( \log n ) \) rebalancings: each rebalancing restores a subtree whose height drops by 1, which unbalances its parent, whose shorter side it was, and so on every other level at least. rebalancings() counts them and their rotations, and the test of the exercise checks both claims, at most one rebalancing (and two rotations) per insertion, random or increasing, and at least \( h / 2 - 1 \) for the removal from the tree of Fibonacci of height \( h \), built level by level with no rotation, for \( h \) from 6 to 22. The AVL tree, shallower (\( 1.44 \log_2 n \) against \( 2 \log_2 n \)), searches faster, the red-black tree changes less; the benchmark bench/ssets.cpp measures the searches, the insertions and the removals of all the sorted sets of the book on random, sorted and reverse-sorted keys (exercise 9.14).

Aggregates that change

The augmented maps of Augmented maps keep an aggregate inside the tree; this section is concerned with how the aggregate follows a change of one value, with two queries that descend the tree by the aggregates, and with the aggregate kept outside the tree by an observer of its events (see Typed modifications). JoinTree tells Inserted, Erased and Assigned of a key, whose handle is the key itself, Cleared when its nodes are taken out (by clear(), or by a bulk operation that consumes it) and Rebuilt when a bulk operation puts its nodes back; each event is sent when the tree is in the state that it describes (an erasure before the removal, with the state that it leaves), so that the events of the operations form a history from the pairs before to the pairs after, and the net effect of a batch is one by the coalescing lemma of Typed modifications. With no observer the mutators are the code of the tree with no policy, which bench/zerocost.py checks by the counts of the instructions and by the code.

An augmentation may declare that \( \otimes \) commutes (commutative), that it has the inverses \( a^{-1} \) of a group (inverse()), and that \( a \otimes b \in \{ a , b \} \) (selective), which the concepts of Algebra.h read (see The algebra of the aggregates); a value is exact if its type is not a floating one.

Lemma 13 (an assignment by its difference). Let the value of the key \( k \), at the node \( u \), change from \( w \) to \( v \), and let \( ( A , \otimes ) \) be an abelian group. Combining the value of every node of the path from the root to \( u \) with

\[ d = g( k , v ) \otimes g( k , w )^{-1} \tag{11} \]

keeps (5) at every node, by \( \delta + 2 \) combinations for \( u \) at the depth \( \delta \), against the \( 2 ( \delta + 1 ) \) combinations and \( \delta + 1 \) values of \( g \) of the recomputation from the children.

Indeed, a node off the path keeps its subtree and its value; for a node \( x \) of the path, associativity and commutativity give \( \mathit{aug}( x ) = B \otimes g( k , w ) \), with \( B \) the combination of the other pairs of its subtree, and the new value \( B \otimes g( k , v ) \) is \( \mathit{aug}( x ) \otimes d \). The lemma needs both hypotheses: without commutativity \( g( k , w ) \) sits between two parts of \( B \), and the floating sums are not associative, so that assign() recomputes in those cases.

Let \( \mathrm{pre}( x ) \) be the combination of the pairs with keys not larger than \( x \). A predicate \( p \) is monotone on the prefixes if \( p( \mathrm{pre}( x ) ) \) implies \( p( \mathrm{pre}( y ) ) \) for \( x < y \), and a predicate \( q \) distributes if \( q( e ) \) is false and \( q( a \otimes b ) = q( a ) \lor q( b ) \).

Lemma 14 (the selection by a prefix). For \( p \) monotone on the prefixes, the descent that goes to the left subtree \( L \) of the current node when \( L \) is not empty and \( p( a \otimes \mathit{aug}( L ) ) \) holds, stops at the node when \( p( a \otimes \mathit{aug}( L ) \otimes g( u ) ) \) holds, and goes right otherwise, \( a \) being the combination of the pairs before the subtree of the current node, finds the smallest \( x \) with \( p( \mathrm{pre}( x ) ) \) in at most \( h + 1 \) rounds, or finds that there is none (augSelect()).

The invariant is that the answer, if it exists, is in the subtree of the current node: going left, \( \max L \) satisfies \( p \), hence the answer is in \( L \); otherwise, by monotonicity, no key of \( L \) satisfies it, and either the node is the answer or the answer is to its right.

Lemma 15 (the filter by the aggregates). For \( q \) distributive, \( q( \mathit{aug}( u ) ) \) holds if and only if a pair of the subtree of \( u \) has \( q( g( x , v ) ) \), and the visit that enters only such subtrees gives those pairs, by increasing keys; for \( m \) pairs given, it enters at most \( m ( h + 1 ) \) nodes, the ancestors of the pairs given, and calls \( q \) at most \( 3 m ( h + 1 ) + 1 \) times (augFilter()).

The first claim follows from (5) by induction, and every node entered is an ancestor of a pair given, or that pair. Sun, Ferizovic and Blelloch build the filtered tree instead, in \( O( m \log( n / m + 1 ) ) \) work for the trees balanced by weight.

Lemma 16 (the aggregate of an observer). If \( \otimes \) is associative, commutative and selective, then \( x \prec y \), i.e., \( x \ne y \) and \( x \otimes y = x \), is a strict total order, and the combination of a nonempty multiset is its least element. Hence an observer of the events of a dictionary of \( m \) pairs keeps the combination of their values by \( O( 1 ) \) combinations per event for an abelian group (an insertion combines, an erasure combines the inverse, an assignment both), by \( O( \log m ) \) comparisons per event for a selective monoid (the multiset of the values in the order \( \prec \)), and, for any other commutative monoid, by one combination per insertion and a recomputation from the structure, in \( O( m ) \), at the first query after an erasure or an assignment (MaterializedAggregate).

For \( x \ne y \) exactly one of \( x \prec y \) and \( y \prec x \) holds, by selectivity and commutativity, and \( x \prec y \prec z \) gives \( x \otimes z = x \otimes ( y \otimes z ) = x \) by associativity; since \( x \otimes y \) is then the least of the two, the combination of a multiset is its least element. A commutative aggregate is that of the multiset of the values, which each event changes by one insertion or erasure of a value, or both. The aggregate of a group of floating values drifts by the rounding of its differences; the observer recomputes it from the structure every Period changes (1024 by default), and its audit compares it with the recomputation within a relative tolerance.

References

See also
A. Montresor, Algoritmi e Strutture Dati, 2025, chapters 5 and 6, https://algoritmicamente.it/materiali/libro/capitoli/cap05.pdf and https://algoritmicamente.it/materiali/libro/capitoli/cap06.pdf
D. E. Knuth, The Art of Computer Programming, vol. 1, 3rd ed., Addison-Wesley, 1997, sections 2.3.1 (the traversal of binary trees, the threads) and 2.3.2 (the binary representation of trees)
A. V. Aho, J. E. Hopcroft, J. D. Ullman, Data Structures and Algorithms, Addison-Wesley, 1983, chapter 3 (the representations of trees)
A. J. Perlis, C. Thornton, Symbol manipulation by threaded lists, Communications of the ACM 3(4), 195-204, 1960, doi:10.1145/367177.367202
J. Vuillemin, A unifying look at data structures, Communications of the ACM 23(4), 229-239, 1980, doi:10.1145/358841.358852
D. Harel, R. E. Tarjan, Fast algorithms for finding nearest common ancestors, SIAM Journal on Computing 13(2), 338-355, 1984, doi:10.1137/0213024
J. W. J. Williams, Algorithm 232: Heapsort, Communications of the ACM 7(6), 347-348, 1964, doi:10.1145/512274.3734138
R. W. Floyd, Algorithm 245: Treesort 3, Communications of the ACM 7(12), 701, 1964, doi:10.1145/355588.365103
R. Hayward, C. McDiarmid, Average case analysis of heap building by repeated insertion, Journal of Algorithms 12(1), 126-153, 1991, doi:10.1016/0196-6774(91)90027-V
R. Seidel, C. R. Aragon, Randomized search trees, Algorithmica 16(4-5), 464-497, 1996, doi:10.1007/BF01940876
D. D. Sleator, R. E. Tarjan, Self-adjusting binary search trees, Journal of the ACM 32(3), 652-686, 1985, doi:10.1145/3828.3835
G. M. Adelson-Velsky, E. M. Landis, An algorithm for the organization of information, Soviet Mathematics Doklady 3, 1259-1263, 1962
L. J. Guibas, R. Sedgewick, A dichromatic framework for balanced trees, Proceedings of the 19th FOCS, 8-21, 1978, doi:10.1109/SFCS.1978.3
G. E. Blelloch, D. Ferizovic, Y. Sun, Just join for parallel ordered sets, Proceedings of the 28th ACM Symposium on Parallelism in Algorithms and Architectures (SPAA), 253-264, 2016, doi:10.1145/2935764.2935768
G. E. Blelloch, D. Ferizovic, Y. Sun, Joinable parallel balanced binary trees, ACM Transactions on Parallel Computing 9(2), 1-41, 2022, doi:10.1145/3512769
Y. Sun, D. Ferizovic, G. E. Blelloch, PAM: parallel augmented maps, Proceedings of the 23rd ACM SIGPLAN Symposium on Principles and Practice of Parallel Programming (PPoPP), 290-304, 2018, doi:10.1145/3178487.3178509
G. E. Blelloch, M. Reid-Miller, Fast set operations using treaps, Proceedings of the 10th ACM Symposium on Parallel Algorithms and Architectures (SPAA), 16-26, 1998, doi:10.1145/277651.277660
S. Adams, Efficient sets: a balancing act, Journal of Functional Programming 3(4), 553-561, 1993, doi:10.1017/S0956796800000885
J. Nievergelt, E. M. Reingold, Binary search trees of bounded balance, SIAM Journal on Computing 2(1), 33-43, 1973, doi:10.1137/0202005
F. K. Hwang, S. Lin, A simple algorithm for merging two disjoint linearly ordered sets, SIAM Journal on Computing 1(1), 31-39, 1972, doi:10.1137/0201004
M. R. Brown, R. E. Tarjan, A fast merging algorithm, Journal of the ACM 26(2), 211-226, 1979, doi:10.1145/322123.322127
R. E. Tarjan, Data Structures and Network Algorithms, SIAM, 1983, chapter 4 (the join of the Red-Black trees), doi:10.1137/1.9781611970265
R. Bayer, E. M. McCreight, Organization and maintenance of large ordered indexes, Acta Informatica 1(3), 173-189, 1972, doi:10.1007/BF00288683
D. Comer, The ubiquitous B-tree, ACM Computing Surveys 11(2), 121-137, 1979, doi:10.1145/356770.356776
A. Aggarwal, J. S. Vitter, The input/output complexity of sorting and related problems, Communications of the ACM 31(9), 1116-1127, 1988, doi:10.1145/48529.48535
S. Chen, P. B. Gibbons, T. C. Mowry, Improving index performance through prefetching, Proceedings of SIGMOD 2001, 235-246, 2001, doi:10.1145/375663.375688
G. Graefe, Modern B-tree techniques, Foundations and Trends in Databases 3(4), 203-402, 2011, doi:10.1561/1900000028
T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, 3rd ed., MIT Press, 2009, chapter 18
D. D. Sleator, R. E. Tarjan, A data structure for dynamic trees, Journal of Computer and System Sciences 26(3), 362-391, 1983, doi:10.1016/0022-0000(83)90006-5
R. E. Tarjan, R. F. Werneck, Dynamic trees in practice, ACM Journal of Experimental Algorithmics 14, article 4.5, 2009, doi:10.1145/1498698.1594231
P. Morin, Open Data Structures (in C++), Edition 0.1G, 2013, https://opendatastructures.org/ods-cpp.pdf, chapters 6 to 9 and 14
C. Martínez, S. Roura, Randomized binary search trees, Journal of the ACM 45(2), 288-323, 1998, doi:10.1145/274787.274812
M. Pătraşcu, M. Thorup, The power of simple tabulation hashing, Journal of the ACM 59(3), 14:1-14:50, 2012, doi:10.1145/2220357.2220361
I. Galperin, R. L. Rivest, Scapegoat trees, Proceedings of the 4th ACM-SIAM Symposium on Discrete Algorithms (SODA), 165-174, 1993
A. Andersson, Improving partial rebuilding by using simple balance criteria, Algorithms and Data Structures (WADS 1989), Lecture Notes in Computer Science 382, 393-402, 1989, doi:10.1007/3-540-51542-9_33
A. Andersson, General balanced trees, Journal of Algorithms 30(1), 1-18, 1999, doi:10.1006/jagm.1998.0967
M. H. Overmars, The Design of Dynamic Data Structures, Lecture Notes in Computer Science 156, Springer, 1983, doi:10.1007/BFb0014927
A. Andersson, Balanced search trees made simple, Algorithms and Data Structures (WADS 1993), Lecture Notes in Computer Science 709, 60-71, 1993, doi:10.1007/3-540-57155-8_236
R. Sedgewick, Left-leaning red-black trees, Department of Computer Science, Princeton University, 2008