Overview
Curated: · Written: · Reviewed:
Trees
In one line
A tree is a node whose children are trees, so most tree algorithms are a base case for a null node, recursive calls on the children, and a combination step. Reach for a binary search tree when you need ordered or range queries over keys, and only quote logarithmic cost if the tree is balanced, because sorted input turns a plain BST into a list.
Key definitions
- Depth: edges from the root down to a node. Known on the way down, so it is passed as a parameter.
- Height: edges on the longest downward path to a leaf (a leaf has height 0). Known on the way up, so it is returned.
- Ordering invariant: every key in the left subtree is smaller than the node, and every key in the right subtree is larger. It constrains whole subtrees.
- Inorder successor: the leftmost node of the right subtree, used to replace a node that has two children.
- Balance condition: the rule (AVL height difference at most 1, red-black no path more than twice another, B-tree uniform depth) that keeps height logarithmic.
- Threaded link: a temporary right pointer to an inorder successor, as used by the Morris traversal.
Formulas and complexity
How it works
- Each recursive call handles one node: return the base value for null, recurse on the children, then combine. Depth flows down as a parameter and height flows up as a return value.
- A BST search follows one edge per comparison, so its cost is the length of the path it walks, which is h.
- A rotation relinks a constant number of nodes and keeps the inorder sequence unchanged, so balance is restored without breaking the ordering invariant.
When to use and when not to
| Situation | Choose | Why |
|---|---|---|
| Exact-key lookup only | Hash map | O(1) expected; no ordering is used |
| Floor, ceiling, range, ordered iteration | Ordered tree map | Hash map needs a full scan |
| Data that is hierarchical (parent and child) | Tree | The hierarchy is the model |
| Keys inserted in sorted order into a plain BST | Neither as written | Height becomes n; use a balanced tree |
| Ordered map in production | Library ordered map | Deletion is where hand-written trees fail |
| Memory-constrained, single thread, need O(1) extra space | Morris traversal | Mutates the tree while it runs |
Traps interviewers probe
- Quoting O(log n) for a search tree without the balance condition. Fix: state the cost as O(h), then say what makes h logarithmic. Sorted insertion of 65,536 keys makes the lookup for the largest key take 65,536 comparisons.
- Validating only that each node sits between its children. Fix: carry an open (low, high) interval down the recursion, narrowing it at each node. A deep node in the right subtree can be smaller than the root.
- Returning 0 for a null child in max or sum code. Fix: a 0 from an absent child beats every negative value, so tree_max over all-negative keys returns 0. Return negative infinity for the null case, or start from the first real node.
- Returning the turning path to the parent in path sum or diameter. Fix: return the best one-sided gain to the parent, and record the candidate that turns at the node in a separate global. The diameter does not need to pass through the root.
- Running Morris traversal while readers search the tree. Fix: the traversal threads right pointers, so a lookup can follow a thread back into a cycle. Lookups for 25 and 45 spin in the guide's example while the job runs, and only single-threaded use is safe.
Interview tips
Open with the structure and the query: 'A BST gives O(h) operations, logarithmic only when the tree is balanced, so for ordered queries I would use the library's ordered map.'
Follow-ups to expect:
- Validate a BST: inherited open interval, with the counterexample where a deep node violates the root.
- Delete a node with two children: replace it with the inorder successor (leftmost node of the right subtree), copy its value, then delete the successor. Promoting an arbitrary child breaks the invariant.
- Serialise a tree: preorder with explicit null markers, or preorder plus inorder. Preorder alone is ambiguous.
- LCA: descend by key comparisons in a BST; use a postorder report-and-meet on a general binary tree.
- Recursion limit: an inorder recursion on 50,000 sorted keys raises RecursionError at CPython's default limit of 1000. Switch to an explicit stack.
- AVL versus red-black: AVL is stricter, so lookups are faster and writes need more rotations. Red-black tolerates more imbalance and rotates less on writes.
30-second answer outline:
- Name the structure and the query it serves.
- State the cost as O(h), and the balance condition that makes h logarithmic.
- Give the invariant and the local-check trap that breaks it.
- Say what you would ship: the library ordered map, or a B-tree when the data lives on disk.
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.