Trees
Hierarchies of nodes - and the ways to walk them.
- current
- not reached yet
- result
Start at 3
3 isn’t empty, so recurse into the left child first.
VARIABLES
- node
- 3
- left
- -
- right
- -
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
A binary tree node has a value and up to two children. Traversals visit nodes depth-first (preorder, inorder, postorder) or level by level.
Why it matters
File systems, HTML, org charts and expression parsers are trees, and recursion handles them naturally.
Think of it like this
A family tree: you can explore one branch fully before moving to the next.
Use it when
- Hierarchical data
- Answers that combine results from the left and right subtrees
- Level-based questions (BFS)
Avoid it when
- Flat sequential data - arrays are simpler
- Very deep, skewed trees with plain recursion in Python
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Any depth-first traversal | O(n) | O(h) stack |
| Level order with a queue | O(n) | O(w) for width w |
| Find a value (no ordering) | O(n) | O(h) |
Often confused with: binary search trees - they add an ordering rule that general binary trees don’t have.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- Most tree answers are “solve left, solve right, combine”
- Recursion depth equals tree height - O(log n) if balanced, O(n) if skewed
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Forgetting the None base case
- Mixing up depth counted in edges vs nodes - ask which the prompt means
- Using a global variable without resetting it between test cases
Edge cases to test
- Empty tree (root is None)
- A single node
- A skewed tree - like a linked list, depth n
Knowledge check
Quick check to lock in the intuition.
Which traversal visits a node after both of its subtrees?
Practice
Apply what you just watched on real interview problems.