Skip to the page

Recursion, trees and heaps · core

Trees and traversals

A tree is visited depth-first (pre-, in- or post-order, with recursion or a stack) or breadth-first level by level with a queue, and most tree questions are one small DFS that combines the answers of the children.

The notes

What you must know

  • DFS pre-order (node, then children) for copying or writing out a tree; post-order (children, then node) for heights, sizes and 'combine results'; in-order on a binary search tree gives sorted order.
  • BFS with a queue gives level order; to process one level at a time, take the queue's size at the start of the level and loop that many times (or use a head index).
  • Height: 1 + max(height of left, height of right), with 0 for an empty tree (say if you count nodes or edges). Counting, summing and finding a path are all small DFS functions.
  • Lowest common ancestor (binary tree): post-order; return the node if it matches p or q; the first node where both sides return a node is the LCA. With parent pointers, walk up from both nodes.
  • Iterative DFS with an explicit stack avoids recursion limits on very deep trees (a skewed tree with 100,000 nodes is 100,000 calls deep).
  • A binary search tree is valid only if every node fits the range set by ALL its ancestors, not just its parent: pass (low, high) down.
  • n-ary trees (file trees, org charts) use the same ideas with a list of children; Employee Importance is a DFS over an id-to-employee map.

The red pen

Common traps: mistake → fix

  • Mistake: BFS by recursion

    Fix: recursion is depth-first; BFS needs a queue.

  • Mistake: BST rules apply to any binary tree

    Fix: LCA by value comparison works only on a BST.

  • Mistake: Assume both nodes exist in LCA

    Fix: ask; otherwise check that both were found.

  • Mistake: A BST is valid if each node is larger than its left child and smaller than its right child

    Fix: a deeper node can still break the order; check the full range.

Easy to hard

Questions interviewers ask, easy to hard

  1. Maximum depth of a binary tree.
  2. Level-order traversal returning one list per level.
  3. In-order traversal without recursion.
  4. Lowest common ancestor in a binary tree; then with parent pointers.
  5. Validate a binary search tree.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview