Trees, Heaps & Search Trees
Hierarchies that keep data ordered, prioritized and quick to query.
A million keys fit in a binary tree only 20 levels deep, so a search that starts at the top reaches any of them in at most 20 steps. Trees like that sit inside databases, file systems, schedulers and route planners. They come in three big shapes: search trees that keep data in order, heaps that keep the smallest item on top, and segment trees that answer questions about whole ranges at once.
What you’ll learn
- Name the parts of a tree (root, parent, child, leaf, subtree) and measure depth and height in edges.
- List a tree's nodes in preorder, inorder, postorder and level order, and choose the order a task needs.
- Explain why every binary-search-tree operation costs time proportional to the height, and how balanced trees keep that height near .
- Trace insertion and extract-min in a heap stored in an array, and describe how a segment tree answers range sums while values change.
- Decide from a problem's wording whether it needs a balanced search tree, a heap or a segment tree.
One root, many branches
Open a folder on your computer. It holds files and more folders, which hold more files and folders, and so on down. Follow any item upward and you always reach the same top folder, along exactly one route. That shape is a tree.
Trees are everywhere in computing: the folders on a disk, the elements of a web page (the <html> element contains <head> and <body>, which contain everything else), a company's org chart, the chapters and sections of a book, the possible move sequences of a game.
projects/ depth 0 ← the root
├── site/ depth 1
│ ├── index.html depth 2 ← a leaf
│ └── img/ depth 2
│ └── logo.png depth 3 ← a leaf
└── notes.txt depth 1 ← a leafA folder tree, drawn the way the tree command prints it. Every item except projects/ sits inside exactly one folder, its parent. The longest path from the root down to a leaf, from projects/ to logo.png, has 3 edges, so this tree has height 3.
Think first A tree has 12 nodes. How many edges does it have, whatever its shape?
- Every node except the root hangs from its parent by exactly one edge, and every edge joins a node to its parent, so a tree with nodes always has exactly edges.
Four ways to visit every node
A binary tree is a tree in which every node has at most two children, a left one and a right one. It also has a neat recursive description: a binary tree is either empty, or a root with a left binary tree and a right binary tree hanging below it.
Many tasks must visit every node once: printing, copying, adding up, searching. Such a walk is a traversal, and the classic ones differ only in when a node is visited compared with its subtrees:
- Preorder: the node first, then its left subtree, then its right subtree.
- Inorder: the left subtree, then the node, then the right subtree.
- Postorder: both subtrees first, the node last.
- Level order: depth 0, then depth 1, then depth 2, each level from left to right.
| Order | Visits a node | A natural job |
|---|---|---|
| Preorder | before its subtrees | Copy a tree, or print an outline: a chapter heading comes before its sections |
| Inorder | between its left and right subtrees | Read the keys of a binary search tree in sorted order (next screen) |
| Postorder | after its subtrees | Combine the children's answers: a folder's total size, a tree's height, deleting a tree |
| Level order | depth by depth, using a queue | Nearest first: the shallowest node with some property, printing level by level |
Spot it: a task on nested data in which each item's answer depends on its children's answers (sizes, totals, heights) calls for a postorder walk; one that must handle a parent before its children (copying, printing an outline) calls for preorder. Now run the one walk you have not tried, inorder, and look closely at its output. It is no coincidence, as the next screen shows.
Binary search trees: one path down
Look at the numbers in that tree. Everything in 50's left subtree is smaller than 50, everything in its right subtree is larger, and the same holds at every node. That is the binary-search-tree property, and a tree that has it is a binary search tree (BST). Inorder lists the left subtree (all smaller), then the node, then the right subtree (all larger), so it always comes out sorted.
The property turns searching into a game of higher-or-lower. To find 60, compare it with the root, 50: 60 is larger, so it can only be in the right subtree. Compare with 70: smaller, go left. Compare with 60: found, after 3 comparisons. Each comparison throws away a whole subtree, so a search visits at most one node per level. To insert a key, search for it, and hang it exactly where the search falls off the tree.
In the starting tree (50 at the root; 30 and 70 below it; 20, 40, 60 and 80 at the bottom), how does a search for 75 go?
- It compares 75 with all 7 keys, since only that proves 75 is absent
- It stops after 1 comparison, because 75 is not the root
- It compares with 50, 70 and 80, then falls off the tree below 80: 75 is not stored
- It compares with 50 and 70, then stops, because 70 has no larger child
Show the answer
C. It compares with 50, 70 and 80, then falls off the tree below 80: 75 is not stored
75 > 50, so go right; 75 > 70, go right; 75 < 80, go left, and 80 has no left child. Three comparisons prove that 75 is absent: if it were stored, the BST property would put it exactly in that empty spot.
Height is everything
A search walks down one path, one comparison per level, so its cost is set by the tree's height. How short can a tree be? Each full level doubles the room, so a binary tree of height holds at most
How tall can a tree be? A plain BST has no say in its own shape: the order in which keys arrive decides it. You insert in increasing order into an empty BST. What is the height of the resulting tree?
Show the answer
14 edges
Each new key is larger than everything before it, so it goes right at every node and becomes the right child of the previous key. The tree is a path of 15 nodes, with height 14 (edges, not nodes). Building it costs comparisons, and a search for 15 makes 15. With every level full, 15 keys would fit in height 3.
Spot it: a problem that needs order and change at once, with insertions and deletions mixed with questions like "the next larger value" or "the closest value to ", calls for a balanced search tree. In practice that means your library's ordered set or map: C++ std::set and std::map, Java TreeSet and TreeMap.
Heaps: the smallest on top
Sometimes you need only the most urgent item, again and again: the next event in a simulation, the closest unvisited city in a route planner, the highest-priority job. A heap does exactly that and nothing more.
A min-heap is a binary tree with the heap property: every node is smaller than or equal to its children. Follow any path down and the values never decrease, so the minimum is always at the root. Unlike a BST, a heap says nothing about left versus right: two siblings can be in either order.
A heap is also a complete binary tree: every level is full except perhaps the last, which fills from the left. That shape needs no pointers at all. Number the nodes level by level, , store them in an array in that order, and the children of index are at and , its parent at .
- Insert: put the new value in the next free cell, at the end of the array, then sift it up: while it is smaller than its parent, swap the two.
- Extract the minimum: take the root, move the last entry into its place, then sift it down: while it is larger than its smaller child, swap it with that child.
Each swap moves one level, and a complete tree with entries has height , so both operations take time.
Spot it: "repeatedly take the smallest (or largest)", "the largest items of a stream", "merge sorted lists", "process events in time order" all call for a heap, which libraries call a priority queue. Python's heapq is a min-heap; C++'s std::priority_queue keeps the largest on top by default.
Segment trees: totals for every range
One more kind of question. An array holds numbers, say the sales of each day, and two operations arrive mixed in any order: change one day's value, and report the total from day to day .
- Adding up on demand costs up to additions per query.
- Precomputed prefix sums answer any total with one subtraction, but changing one value changes every prefix sum after it: up to updates.
A segment tree makes both operations fast. Its root stores the total of the whole array, its two children the totals of the left and right halves, their children the quarters, and so on down to single elements.
| Approach | Total of | Change one value |
|---|---|---|
| Plain array | up to additions | 1 step |
| Prefix sums | 1 subtraction | up to updates |
| Segment tree |
Spot it: many questions about ranges of an array (sum, minimum, maximum) mixed with updates call for a segment tree, or, for sums, its compact cousin the Fenwick tree. If the array never changes, prefix sums are simpler and faster.
Which tree for which problem?
Each structure in this lesson answers one kind of question fast because it keeps one invariant, and the invariant tells you when to reach for it.
| Structure | Invariant | Fast operations | Reach for it when |
|---|---|---|---|
| Balanced BST | smaller keys left, larger right; height | search, insert, delete, next larger or smaller: | you need order and change at once |
| Heap | every parent its children | read the minimum: ; insert, extract-min: | you repeatedly need the smallest (or largest) |
| Segment tree | each node holds the total of its range | range total, point update: | you need range totals, minimums or maximums while values change |
An emergency room keeps admitting patients, each with an urgency score, and must always treat the most urgent patient next. Which structure fits best?
- A hash table keyed by patient name
- A sorted array of urgency scores
- A max-heap keyed by urgency
- An unsorted list, scanned for the most urgent patient each time
Show the answer
C. A max-heap keyed by urgency
The only question is "who is most urgent?", asked again and again while patients arrive. A max-heap answers it at the root and inserts or removes in . A balanced BST would also work, but it maintains a full order that this problem never uses.
| Optimized lesson | What you will do there |
|---|---|
| Binary Trees & Traversals | Write every traversal recursively and with an explicit stack or queue, rebuild a tree from two of its traversals, and compute heights, diameters and balance in one pass. |
| Binary Search Trees | Implement search, successor and the three cases of deletion, and prove that random insertion orders give an average depth of about . |
| Balanced Trees: AVL, Red-Black & B-Trees | Rebalance with rotations, prove the AVL and red-black height bounds, and see why databases use B-trees with wide nodes. |
| Heaps & Priority Queues | Implement sift-up and sift-down with their invariants, change keys through a position map, build a heap in , sort with heapsort, and solve top-, -way merge and running-median problems. |
| Segment Trees & Fenwick Trees | Build segment trees for any associative operation, prove that a query touches at most four nodes per level, and count inversions with a Fenwick tree, which answers prefix sums using the lowest set bit of an index. |
Key takeaways
- A tree has one root, and every other node has exactly one parent. Depth counts edges from the root; height counts edges on the longest root-to-leaf path (one node: 0, empty tree: ).
- Traversals visit every node once: preorder puts a node before its subtrees, postorder after them, inorder between its left and right subtrees, and level order goes depth by depth.
- A binary search tree keeps smaller keys to the left and larger keys to the right, so each operation follows one path and costs time proportional to the height. Sorted input builds a path; balanced trees rotate to keep the height .
- A heap keeps the minimum at the root of a complete tree stored in an array, with the children of at and ; insert and extract-min sift along one path in .
- A segment tree stores the totals of the halves, quarters and so on of an array, so range queries and point updates both take .
- Order and change at once → a balanced BST; the smallest, again and again → a heap; range totals while values change → a segment tree or Fenwick tree.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A program must report every folder's total size, including everything inside it, in one pass over the folder tree. In which order should it visit the folders?
- Preorder: each folder before its contents
- Level order: the top folder first, then its subfolders, level by level
- Postorder: each folder after all of its contents
- Any order works, since every folder is visited once
Show the answer
C. Postorder: each folder after all of its contents
A folder's total is its own files plus its subfolders' totals, so those must be known first. Postorder visits every node after its children, so each total is ready exactly when it is needed. The same order computes heights, counts and anything else built from the children's answers.
A plain BST receives keys that arrive as increasing timestamps. How many comparisons does a search for the newest key make?
- About , because each comparison halves the remaining keys
- : the tree is a path, and the newest key is at the bottom
- 1: the newest key is placed at the root
- About , the average depth of a key
Show the answer
B. : the tree is a path, and the newest key is at the bottom
Each new key is larger than all earlier ones, so it becomes the right child of the previous key. The tree is a path of height , and the newest key sits at depth , reached after comparisons. Balanced trees exist to prevent exactly this.
A min-heap holds a million numbers. Which request can it not answer quickly?
- Report the smallest number
- Remove the smallest number
- Insert a new number
- Report whether 42 is stored
Show the answer
D. Report whether 42 is stored
The heap property only puts each parent below its children, so 42 could be anywhere under a smaller value, and finding it may mean checking every entry: . The minimum is at the root, , and insertion and extract-min each walk one path, .
An array of numbers receives operations in any order: set to , or report the sum of (both ends included). Which approach fits in about a second?
- A segment tree: per operation, a few million steps in all
- Add up with a loop for each query
- Keep prefix sums, and rebuild them after every change
- A min-heap of the values
Show the answer
A. A segment tree: per operation, a few million steps in all
A segment tree query visits at most about 70 nodes here, and an update 18, so operations take a few million steps: well under a second by the rule of thumb of about simple operations per second. The other two approaches can cost up to steps per operation, about in all.
Why do libraries build their ordered sets and maps (C++ std::set, Java TreeMap) on balanced trees rather than plain BSTs?
- Balanced trees use less memory per key
- Plain BSTs cannot delete keys
- Balanced trees keep the height whatever order the keys arrive in
- Balanced trees keep the keys in insertion order
Show the answer
C. Balanced trees keep the height whatever order the keys arrive in
A plain BST's height depends on the insertion order and reaches on sorted input, which real data often is. Rotations after each update keep a balanced tree's height , so every operation costs in the worst case.
Go deeper
- Binary Trees & Traversals · Preorder, inorder, postorder and level order, and thinking recursively about trees.
- Binary Search Trees · Ordered keys, O(height) operations, and why height is everything.
- Balanced Trees: AVL, Red-Black & B-Trees · Rotations and invariants that guarantee O(log n) height.
- Heaps & Priority Queues · Always know the minimum: sift up, sift down and heapify.
- Segment Trees & Fenwick Trees · Range queries and updates in O(log n).
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapters 6, 12 and 13.
- R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), sections 2.4, 3.2 and 3.3.