ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
BinaryTreeAlgorithms.h File Reference

The classic problems on binary trees and on binary search trees, written once for any representation of the nodes: a node is reached by a pointer, nil is nullptr, and its links and its key are read either by the member functions left(), right(), parent() and read() of BinaryTree [see BinaryTree.h] or by the fields left, right, parent and key of a plain struct, as in the pseudocode of the book. More...

#include "ADS/Contract.h"
#include "ADS/search/RangeMinimum.h"
#include "ADS/tree/BinaryTree.h"
#include <algorithm>
#include <bit>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <type_traits>
#include <utility>
#include <vector>
#include "ADS/tree/impl/BinaryTreeAlgorithms.tpp"

Go to the source code of this file.

Namespaces

namespace  ADS

Concepts

concept  ADS::BinaryNode
 a node of a binary tree: a pointer to a struct whose children are read by left() and right() or by the fields left and right
concept  ADS::ParentBinaryNode
 a node of a binary tree with the link to its parent
concept  ADS::KeyedBinaryNode
 a node of a binary tree with a key
concept  ADS::SizedBinaryNode
 a node of a binary tree with a key and the size of its subtree

Functions

template<ParentBinaryNode N>
N ADS::lowestCommonAncestor (N u, N v)
 the deepest node that is an ancestor of both \( u \) and \( v \), each node being an ancestor of itself; \( O( h ) \) time, \( O( 1 ) \) space
template<KeyedBinaryNode N, KeyedBinaryNode M, class Equal = std::equal_to<>>
bool ADS::equalTrees (N t, M s, Equal eq={})
 whether \( t \) and \( s \) have the same shape and eq( a , b ) holds on the keys \( a \) and \( b \) of each two nodes in the same place; \( O( n ) \) time, \( O( h ) \) space
template<KeyedBinaryNode N, class Compare = std::less<>>
bool ADS::isSearchTree (N t, Compare less={})
 whether the keys of \( t \) are strictly increasing in the invisit, by less; \( O( n ) \) time, \( O( h ) \) space
template<BinaryNode N, class Red>
bool ADS::isRedBlackTree (N t, Red red)
 whether the coloring of \( t \), red( u ) telling whether the node \( u \) is red, respects the constraints of a Red-Black tree: the root black, no red node with a red child, the same number of black nodes on every path from the root down to a leaf nil; \( O( n ) \) time, \( O( h ) \) space
template<KeyedBinaryNode N, class K, class F, class Compare = std::less<>>
std::size_t ADS::searchTreeRange (N t, const K &lo, const K &hi, F &&f, Compare less={})
 f( u ) on the nodes \( u \) of the binary search tree \( t \) whose keys are in \( [ \mathit{lo} , \mathit{hi} ] \), in increasing order of the keys; the number of the nodes examined, at most \( k + 2 ( h + 1 ) \) for \( k \) keys in the range; \( O( h + k ) \) time
template<KeyedBinaryNode N, class K, class Compare = std::less<>>
N ADS::searchTreeFind (N t, const K &k, Compare less={})
 the node of the key \( k \) in the binary search tree \( t \), nil if absent; \( O( h ) \) time
template<KeyedBinaryNode N, class K, class Compare = std::less<>>
auto ADS::searchTreeLookup (N t, const K &k, Compare less={})
 the value of the key \( k \) in the binary search tree \( t \), nothing if absent, by searchTreeFind(); \( O( h ) \) time
template<KeyedBinaryNode N, class K, class Compare = std::less<>>
N ADS::searchTreeLowerBound (N t, const K &k, Compare less={})
 the node of the smallest key not smaller than \( k \) in the binary search tree \( t \), nil if none (the find(x) of an SSet of Morin); \( O( h ) \) time
template<KeyedBinaryNode N, class K, class Compare = std::less<>>
auto ADS::searchTreeFindKey (N t, const K &k, Compare less={})
 the address of the key \( k \) in the binary search tree \( t \), nil if absent (the find(x) of a USet of Morin), by searchTreeLowerBound() and one more comparison; \( O( h ) \) time
template<KeyedBinaryNode N, class K, class Compare = std::less<>>
auto ADS::searchTreeLowerBoundKey (N t, const K &k, Compare less={})
 the address of the smallest key not smaller than \( k \) in the binary search tree \( t \), nil if none, by searchTreeLowerBound(); \( O( h ) \) time
template<KeyedBinaryNode N, class K, class Compare = std::less<>>
auto ADS::searchTreeLowerBoundEntry (N t, const K &k, Compare less={})
 the key and the value of the smallest key not smaller than \( k \) in the binary search tree \( t \) as a pair, nothing if none, by searchTreeLowerBound(); \( O( h ) \) time
template<SizedBinaryNode N>
N ADS::searchTreeSelect (N t, std::size_t i)
 the node of rank \( i \) of the binary search tree \( t \), i.e., with \( i \) smaller keys, by the sizes of the left subtrees; \( O( h ) \) time
template<SizedBinaryNode N, class K, class Compare = std::less<>>
std::size_t ADS::searchTreeRank (N t, const K &k, Compare less={})
 the number of the keys smaller than \( k \) in the binary search tree \( t \), the sizes of the left subtrees passed on the right along the search of \( k \), plus one for each node so passed; \( O( h ) \) time
template<class N, class K, class Compare = std::less<>>
requires KeyedBinaryNode< N * > && std::is_pointer_v< decltype( N::left ) >
N ** ADS::searchTreeLink (N **link, const K &k, std::vector< N * > &P, Compare less={})
 the link at which the key \( k \) is, or would be inserted, in the binary search tree whose root is *link, i.e., the address of the root or of the field left or right of the parent, the nodes passed above it pushed on \( P \) from the root down; the key is there if and only if the node at the link returned is not nil; \( O( h ) \) time
template<class N>
requires BinaryNode< N * > && std::is_pointer_v< decltype( N::left ) >
N * ADS::searchTreeSplice (N **link, std::vector< N * > &P)
 the node at link (as given by searchTreeLink()) taken out of its binary search tree: if it has two children, its key and its value are replaced by those of its successor, which is taken out instead, and the nodes down to the successor are pushed on \( P \); the node taken out is returned, to be freed, and its parent (the last node of \( P \)) links its only child; \( O( h ) \) time
template<ParentBinaryNode N>
N ADS::nextPreorder (N u)
 the node after \( u \) in the previsit of its tree, nil after the last; \( O( 1 ) \) amortized over a whole visit (exercise 6.8 of Morin)
template<ParentBinaryNode N>
N ADS::nextInorder (N u)
 the node after \( u \) in the invisit of its tree, nil after the last; \( O( 1 ) \) amortized over a whole visit (exercise 6.8 of Morin)
template<ParentBinaryNode N>
N ADS::nextPostorder (N u)
 the node after \( u \) in the postvisit of its tree, nil after the root; \( O( 1 ) \) amortized over a whole visit (exercise 6.8 of Morin)
template<BinaryNode N>
N ADS::firstInorder (N u)
 the first node of the invisit of the subtree of \( u \), its leftmost node, from which nextInorder() starts; \( O( h ) \) time
template<BinaryNode N>
N ADS::firstPostorder (N u)
 the first node of the postvisit of the subtree of \( u \), reached by going left when possible and right otherwise, from which nextPostorder() starts; \( O( h ) \) time (the first node of the previsit is \( u \) itself)
template<BinaryNode N>
long ADS::treeHeight (N t)
 the height of the tree \( t \), \( -1 \) if empty, by levels with no recursion: \( O( n ) \) time and \( O( w ) \) space for a tree of width \( w \), on a degenerate tree of any height
template<ParentBinaryNode N>
std::size_t ADS::subtreeSize (N u)
 the number of nodes of the subtree of \( u \), by a walk along the links to the parents that never leaves the subtree, with no recursion and no stack: \( O( n_u ) \) time and \( O( 1 ) \) space (the size2(u) of exercise 6.4 of Morin)
template<ParentBinaryNode N>
long ADS::subtreeHeight (N u)
 the height of the subtree of \( u \), \( -1 \) for nil, by the walk of subtreeSize() that keeps the depth below \( u \): \( O( n_u ) \) time and \( O( 1 ) \) space (the height2(u) of exercise 6.5 of Morin)
template<BinaryNode N>
bool ADS::isSizeBalanced (N t)
 whether every node \( u \) of \( t \) has subtrees whose sizes differ by 1 at most (exercise 6.6 of Morin), by a postvisit that returns the size of each subtree, or stops at the first that is not balanced: \( O( n ) \) time, against the \( \Theta( n \log n ) \) to \( \Theta( n^2 ) \) of a test that computes each size again
template<BinaryNode N, class F>
void ADS::orderNumbers (N t, F &&f)
 f( u , pre , in , post ) on each node \( u \) of \( t \) with its numbers in the previsit, in the invisit and in the postvisit, from 0, in one visit: \( O( n ) \) time, \( O( h ) \) space (exercise 6.7 of Morin).
template<BinaryNode N>
std::vector< bool > ADS::shapeCode (N t)
 the shape of \( t \) in \( 2 ( n - 1 ) \) bits, none for \( n \le 1 \) (exercise 6.11 of Morin): for each node in the previsit but the last, which is a leaf, whether it has a left and whether it has a right child; \( O( n ) \) time.
BinaryTree< std::size_t > * ADS::fromShapeCode (const std::vector< bool > &c, std::size_t n)
 the tree of the shape of shapeCode() above, its values the numbers of the previsit; the caller owns it, nil if \( n = 0 \); \( O( n ) \)
template<KeyedBinaryNode N, class K, class F, class Compare = std::less<>>
std::size_t ADS::lessOrEqual (N t, const K &x, F &&f, Compare less={})
 f( u ) on the nodes \( u \) of the binary search tree \( t \) whose keys are not larger than \( x \), in increasing order, and their number \( n' \); \( O( n' + h ) \) time (the getLE(x) of exercise 6.14 of Morin)
template<class T, class Make, class Compare = std::less<>>
auto ADS::minimumHeightSearchTree (const std::vector< T > &A, Make make, Compare less={}) -> std::invoke_result_t< Make &, const T &, std::nullptr_t, std::nullptr_t >
 the binary search tree of the keys of \( A \) of the least height, the lower middle key at the root of each subtree, whose nodes are made by make( v , l , r ) over the subtrees \( l \) and \( r \), nil if \( A \) is empty; \( O( n ) \) time
template<class T, class Compare = std::less<>>
requires std::predicate< Compare & , const T & , const T & >
BinaryTree< T > * ADS::minimumHeightSearchTree (const std::vector< T > &A, Compare less={})
 the tree of minimumHeightSearchTree() above as a BinaryTree, which the caller owns
template<class T>
BinaryTree< T > * ADS::fromPreorderInorder (const std::vector< T > &pre, const std::vector< T > &in)
 the binary tree whose previsit is pre and whose invisit is in, nil if they are empty; \( O( n ) \) time; the caller owns it
template<class T, class Compare = std::less< T >>
BinaryTree< T > * ADS::cartesianBinaryTree (const std::vector< T > &A, Compare less={})
 the Cartesian tree of \( A \), the leftmost minimum by less at the root, a heap whose invisit is \( A \), nil if \( A \) is empty; \( O( n ) \) time; the caller owns it

Detailed description

The classic problems on binary trees and on binary search trees, written once for any representation of the nodes: a node is reached by a pointer, nil is nullptr, and its links and its key are read either by the member functions left(), right(), parent() and read() of BinaryTree [see BinaryTree.h] or by the fields left, right, parent and key of a plain struct, as in the pseudocode of the book.

The functions that build a tree return a BinaryTree, or take a callable make( v , l , r ) that makes a node of value \( v \) over the subtrees \( l \) and \( r \), for any other representation.

  • lowestCommonAncestor( u , v ) walks up the links to the parents: the deeper node climbs to the depth of the other, then both climb together until they meet, \( O( h ) \) time and \( O( 1 ) \) space for a tree of height \( h \). The usual alternative pushes the two paths on two stacks and pops them while their tops agree, \( O( h ) \) space; with many queries on a fixed tree the reduction of Bender and Farach-Colton to the range minimum on the Euler tour answers in \( O( 1 ) \) after \( O( n ) \) preprocessing [see RangeMinimum.h], as the structure of Harel and Tarjan did first.
  • equalTrees( t , s ) tells whether two trees have the same shape and equal keys in the same places, by a simultaneous visit, \( O( n ) \) time and \( O( h ) \) space; with a comparison always true it compares the shapes only.
  • isSearchTree( t ) checks the order of a binary search tree: each key must lie in the open interval that its ancestors leave to it, and comparing a node with its children only is not enough. The visit carries the two ends down, \( O( n ) \) time and \( O( h ) \) space, the same as checking that the invisit is strictly increasing.
  • isRedBlackTree( t , red ) checks the constraints of a Red-Black coloring (the root black, no red node with a red child, the same number of black nodes on every path down to a leaf nil) by a postvisit that returns the black height of each subtree, \( O( n ) \) time.
  • searchTreeRange( t , lo , hi , f ) reports in increasing order the nodes of a binary search tree whose keys are in \( [ \mathit{lo} , \mathit{hi} ] \), a visit pruned where the key leaves the range: \( O( h + k ) \) time for \( k \) keys reported, since the nodes examined outside the range lie on the two paths that search for \( \mathit{lo} \) and for \( \mathit{hi} \).
  • minimumHeightSearchTree( A ) builds the binary search tree of the sorted keys of \( A \) of the least height, \( \lceil \log_2( n + 1 ) \rceil - 1 \), by putting the middle key at the root and the two halves below, recursively: \( T( n ) = 2 T( n / 2 ) + O( 1 ) = O( n ) \) time and \( O( \log n ) \) stack. The same tree comes from the sorted list in \( O( n ) \) by building the subtrees in symmetric order, and any tree is rebalanced in place, in \( O( n ) \) time and \( O( 1 ) \) space, by the algorithm of Day, Stout and Warren.
  • fromPreorderInorder( pre , in ) rebuilds the binary tree of distinct values whose previsit is pre and whose invisit is in. The first value of pre is the root and splits in into the two subtrees; rather than looking the root up in in, the algorithm keeps a stack of the nodes whose right subtree is still open: the next value of pre is the left child of the top, unless the top is the next value of in, in which case the nodes are popped while they match in and the value becomes the right child of the last one. Each node is pushed and popped once, \( O( n ) \) time, with no table of the places and only the equality of the values.
  • cartesianBinaryTree( A ) is the Cartesian tree of Vuillemin as a BinaryTree: its root is the leftmost minimum of \( A \) and its subtrees the Cartesian trees of the parts before and after it, i.e., the binary tree whose invisit is \( A \) and which is a heap; with std::greater it is the maximal tree, with the maximum at the root. The parents come from cartesianTree() of RangeMinimum.h, which builds them with a stack of the right spine in \( O( n ) \) time, against the \( O( n^2 ) \) of the recursion of the definition on a sorted \( A \).
  • The traversals of chapter 6 of Morin and their exercises: nextPreorder(), nextInorder() and nextPostorder() give the node after a given one in each visit by the links to the parents (exercise 6.8), each node met \( O( 1 ) \) times over a whole visit; subtreeSize() and subtreeHeight() count a subtree by the walk of section 6.1.2 with no recursion and no stack (exercises 6.4 and 6.5); isSizeBalanced() tests that the two subtrees of each node differ by one node at most in \( O( n ) \) (exercise 6.6); orderNumbers() gives the three numbers of each node in one visit (exercise 6.7); shapeCode() and fromShapeCode() write and read a shape in \( 2 ( n - 1 ) \) bits (exercise 6.11); lessOrEqual() reports the keys not larger than \( x \) in \( O( n' + h ) \) (exercise 6.14). The parents give the traversals of BinaryTree.h too, as ranges.

The contracts [see Contract.h]: lowestCommonAncestor() needs two nodes of the same tree and returns a common ancestor none of whose children is one (a postcondition); searchTreeRange() needs \( \mathit{lo} \le \mathit{hi} \); minimumHeightSearchTree() needs the keys strictly increasing and returns a tree of the least height (an audit); fromPreorderInorder() needs two visits of the same length and checks that the invisit of the tree built is in, which fails exactly when no tree of distinct values has those two visits; cartesianBinaryTree() returns a tree whose invisit is \( A \) (an audit). The functions are defined in BinaryTreeAlgorithms.tpp.

See also
A. Montresor, Algoritmi e Strutture Dati, 2025, sections 5.5, 6.1 and 6.2, https://algoritmicamente.it/materiali/libro/capitoli/cap05.pdf
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
M. A. Bender, M. Farach-Colton, The LCA problem revisited, Proceedings of the 4th Latin American Symposium on Theoretical Informatics (LATIN), LNCS 1776, 88-94, 2000, doi:10.1007/10719839_9
P. Morin, Open Data Structures (in C++), Edition 0.1G, 2013, https://opendatastructures.org/ods-cpp.pdf, section 6.1 and exercises 6.4 to 6.14
Q. F. Stout, B. L. Warren, Tree rebalancing in optimal time and space, Communications of the ACM 29(9), 902-908, 1986, doi:10.1145/6592.6599
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
Author
Donato Meoli
Dipartimento di Informatica
Università di Pisa