Bitpath

Trees & Heaps

Data that branches. Walk binary trees depth-first and level by level, keep values searchable in a binary search tree, pull the smallest item from a heap in O(log n), and store words by their prefixes in a trie.

  • Intermediate
  • 4 units, 12 lessons, 135 exercises
  • Python, JavaScript or TypeScript
  • Builds on Recursion & Backtracking, Data Structures

Unit 01 · 3 lessons

Binary trees

Read, measure and walk a binary tree, depth-first and level by level

  1. > start01Roots and leaves
  2. 02Three ways down
  3. BOSSLevel by level
Unit prize
  1. 01
    Roots and leaves

    Nodes, links, and measuring a tree with recursion

  2. 02
    Three ways down

    Pre-order, in-order and post-order traversal

  3. BOSS
    Level by level

    Breadth-first traversal with a queue, grouped by level

Read the unit guide

A binary tree is made of nodes. Each node holds a value and two links, left and right, and either link may be empty. The node at the top is the root; a node with no children is a leaf. Your code only ever holds the root: everything else is reached by following links down.

Every child is itself the root of a smaller tree, so tree functions are recursive almost by default. Handle the empty tree first (that is the base case), then combine the answers from the left and right subtrees. Size is 1 + size(left) + size(right). Height is 1 + the taller of the two.

Height matters more than size. A tree with n nodes can be as short as about log₂ n levels (bushy) or as tall as n levels (a chain). Most tree operations cost time proportional to the height. This course counts height in levels: an empty tree has height 0, a single node has height 1.

A depth-first walk goes all the way down the left before it touches the right. The three classic orders differ only in when the node itself is handled: before its subtrees (pre-order), between them (in-order) or after them (post-order). Each visits every node once, so O(n) time, and uses O(height) memory for the call stack.

A breadth-first walk visits level by level using a queue: take a node from the front, add its children to the back. To group values by level, note the queue's size when a level starts and remove exactly that many nodes. BFS is also O(n) time, but its queue can hold a whole level, up to about n/2 nodes.

The classic pitfall is forgetting the empty tree. Any function that touches node.left without first checking that node exists will crash at the first leaf.

Unit 02 · 3 lessons

Binary search trees

Keep values in a tree so that search, insert and sorted output stay cheap

  1. 01The ordering rule
  2. 02Insert and balance
  3. BOSSIs it a BST?
Unit prize
  1. 01
    The ordering rule

    Search in O(height), and in-order comes out sorted

  2. 02
    Insert and balance

    Insertion, and why sorted input ruins the tree

  3. BOSS
    Is it a BST?

    Validate with bounds passed down, then find the k-th smallest

Read the unit guide

A binary search tree (BST) keeps one promise at every node: everything in its left subtree is smaller, everything in its right subtree is larger. The promise covers whole subtrees, not just the two children.

That promise makes search a single walk downward. Compare with the node: equal means found, smaller means go left, larger means go right. If you fall off the tree, the value is not there. Each comparison discards a whole subtree, so the cost is O(height). It is binary search, drawn as a tree.

Insert is the same walk: go down as if searching, and attach the new value at the empty spot where the search falls off. New values always become leaves. The smallest value is as far left as you can go, the largest as far right, and an in-order traversal visits everything in sorted order.

The catch is the height. Insert values in a lucky order and the tree has about log₂ n levels. Insert them already sorted and every value goes right: the tree becomes a chain with n levels, and every operation is O(n). Self-balancing trees (AVL, red-black) rotate nodes on insert to keep the height at O(log n).

To check that a tree really is a BST, comparing each node with its children is not enough: a value can be fine next to its parent and still be on the wrong side of a grandparent. Pass a range down instead. Going left lowers the upper bound to the parent's value, going right raises the lower bound, and every node must sit strictly inside its range.

Equivalently, a tree is a BST exactly when its in-order traversal is strictly increasing. That same fact gives you the k-th smallest value: it is the k-th one in-order visits.

Unit 03 · 3 lessons

Heaps

Always know the smallest item, with O(log n) push and pop

  1. 01A tree in an array
  2. 02Sift up, sift down
  3. BOSSTop K
Unit prize
  1. 01
    A tree in an array

    The heap rule, complete trees and index maths

  2. 02
    Sift up, sift down

    Push and pop in O(log n), traced by hand

  3. BOSS
    Top K

    Keep the k largest of a stream with a tiny heap

Read the unit guide

Some jobs only ever ask one question: what is the smallest item right now? A task scheduler wants the most urgent job, a route finder the closest unexplored place. Keeping everything sorted answers that, but every arrival costs O(n) to slot in. A heap answers it with O(log n) per change.

A min-heap is a binary tree with one rule: every parent is less than or equal to its children. That puts the minimum at the root. Nothing is promised about left versus right, so a heap is only loosely ordered, and that looseness is what makes it cheap to maintain.

The tree is always complete: every level full, the last one filled from the left. With no gaps, it can be stored level by level in a plain array with no node objects. The children of index i are at 2i + 1 and 2i + 2, and its parent is at (i - 1) // 2. A complete tree with n items has about log₂ n levels, always. Unlike a search tree, a heap cannot degenerate into a chain.

To push, append the value at the end and sift it up: swap with its parent while it is smaller. To pop the minimum, take the root, move the last item into its place and sift it down: swap with the smaller child while that child is smaller. Each walks one root-to-leaf path, so both are O(log n). Reading the minimum is O(1). Finding an arbitrary value is still O(n).

Python ships this as the heapq module, which works on an ordinary list. JavaScript and TypeScript have no built-in heap, so you write push and pop yourself: about twenty lines over an array.

The classic use is top-k: to keep the k largest items of a long stream, hold a min-heap of only k items. Its root is the weakest keeper, and anything that pushes the heap past k evicts it. That costs O(n log k) and never stores more than k + 1 items. And popping a heap until it is empty returns everything in sorted order, which is heap sort.

Unit 04 · 3 lessons

Tries

Store words by their prefixes and answer prefix questions fast

  1. 01Shared prefixes
  2. 02Insert, search, starts-with
  3. BOSSAutocomplete
Unit prize
  1. 01
    Shared prefixes

    Letters on edges, child maps and the end-of-word flag

  2. 02
    Insert, search, starts-with

    Three walks that cost O(length), and word versus prefix

  3. BOSS
    Autocomplete

    Collect every word under a prefix with a depth-first search

Read the unit guide

A hash set can tell you instantly whether a word is stored, but ask it "which words start with ca?" and it has to look at every word. A trie (say "try") is built for that question. It is the structure behind autocomplete, spell checkers and phone keypads.

A trie is a tree where every edge is one letter, so every path from the root spells a prefix. Words that start the same way share the same first nodes: car, cart and cat all pass through the same c and the same a. A node keeps its children in a map from letter to child node.

Some paths are words and some are only on the way to one. With cart stored, the path c-a-r exists whether or not car is a word. So each node carries a flag that says "a word ends here". Forgetting the flag is the classic trie bug.

Insert walks down the word letter by letter, creates any node that is missing and sets the flag on the last one. Search does the same walk without creating anything, and succeeds only if the path exists and the last node is flagged. Starts-with is the same walk again, and only needs the path. All three cost O(length of the word), however many words are stored.

Autocomplete puts it together: walk the prefix to its node, then run a depth-first search below it, carrying the letters so far and recording the path at every flagged node. The cost is the prefix plus the size of that subtree, and the rest of the dictionary is never touched.

The price is memory: a node per letter, each with its own map. A trie earns that when you need prefix queries, and a hash set stays the better choice when you only ever ask about whole words.

Learn Trees & Heaps on your phone.

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy