Trees are the foundation of hierarchical data organization in computer science β from database indexes (B-trees, Red-Black trees) to file systems, compilers, and network routing. Unlike linear structures, trees enable O(log n) search, insertion, and deletion when balanced, and support complex queries over hierarchical data. This cheat sheet covers every major tree structure and algorithm, from fundamental BST operations through advanced techniques like Heavy-Light Decomposition, Centroid Decomposition, and persistent segment trees used in competitive programming and production systems.
What This Cheat Sheet Covers
This topic spans 15 focused tables and 122 indexed concepts. Below is a complete table-by-table outline of this topic, spanning foundational concepts through advanced details.
Table 1: Binary Search Tree (BST) β Core Properties and Operations
The BST is the starting point for all search trees: a binary tree where every left-subtree key is smaller than the node and every right-subtree key is larger. Understanding its fundamental operations β and its worst-case degeneration β motivates every balanced-tree variant that follows.
| Structure | Example | Description |
|---|---|---|
left.key < node.key < right.key | Every node satisfies: all keys in left subtree < node key < all keys in right subtree; enables O(log n) search on balanced trees. | |
if key < node: go leftelif key > node: go rightelse: found | Compare key with node; recurse left or right; O(log n) balanced, O(n) worst case (degenerate/linked-list tree). | |
BST.insert(5) β walk to null leaf, place node | Search for key until null leaf; insert new node there; O(log n) average, O(n) worst. | |
delete node with 2 children β replace with inorder successor | β’ 0 children: remove directly β’ 1 child: replace node with child β’ 2 children: replace with inorder successor (smallest in right subtree), then delete successor | |
inorder(BST) β [1, 3, 5, 7, 9] | Visiting nodes left β root β right yields keys in sorted ascending order β a unique BST property. | |
floor(6) on {1,3,5,7} β 5ceil(6) β 7 | Floor: largest key β€ query. Ceiling: smallest key β₯ query. Both O(log n) via BST traversal. |