Trees
Tree problems look varied, but almost all of them are one of two traversals with one decision attached. Depth-first search visits a node and recurses into its children; breadth-first search visits the tree level by level with a queue. The decision is where information flows: down from parent to child as arguments, or up from child to parent as return values. Get that decision right before you type and most tree problems take ten lines. This lesson works through both directions, level-order traversal, binary search trees, and what to do when the tree is too deep for recursion. It is for software and data candidates at any level; a later section says what changes as the bar rises. Code is Python.
How tree problems are judged
The SmartIntervu coding report scores problem solving, correctness, code quality, testing and edge cases, and communication. On trees, problem solving means saying out loud what each recursive call returns before writing it. Testing means naming the cases that break tree code: an empty tree, a single node, and a tree that is a long chain (all left children). Most correctness bugs come from a base case that returns the wrong value for None.
Every example uses this node:
from collections import deque
from typing import Optional
class TreeNode:
def __init__(
self,
val: int,
left: "Optional[TreeNode]" = None,
right: "Optional[TreeNode]" = None,
) -> None:
self.val = val
self.left = left
self.right = rightThe cue
You will be told it is a tree, so the cue is about which traversal and which direction:
"depth", "height", "balanced", "diameter", "subtree sums": the answer for a node depends on its children's answers. DFS, return values up.
"root-to-leaf path", "values seen so far", "within a range": a node needs context from its ancestors. DFS, carry state down.
"level", "row", "left or right side view", "nearest to the root": the order of visiting matters by distance from the root. BFS with a queue.
"binary search tree", "kth smallest", "sorted": use the ordering property, usually through an in-order traversal.
DFS that returns values up
Write the function's contract as a sentence before the code: "max_depth(node) returns the number of nodes on the longest path from node down to a leaf." The base case falls out of the sentence: an empty tree has depth 0.
def max_depth(node: Optional[TreeNode]) -> int:
if node is None:
return 0
return 1 + max(max_depth(node.left), max_depth(node.right))Every node is visited once, so time is O(n). Space is O(h) for the call stack, where h is the height: about log n for a balanced tree and n for a chain.
DFS that carries state down
Sometimes the child cannot decide anything without knowing what happened above it. "Is there a root-to-leaf path whose values add up to a target?" needs the remaining amount at each node, so pass it down:
def has_path_sum(node: Optional[TreeNode], remaining: int) -> bool:
if node is None:
return False
remaining -= node.val
if node.left is None and node.right is None:
return remaining == 0
return has_path_sum(node.left, remaining) or has_path_sum(
node.right, remaining
)Two details carry the correctness score. The leaf check happens on the node, not on None: if you returned remaining == 0 for None, a node with one child would count a path that stops halfway. And because remaining is an integer argument, each call has its own copy, so there is nothing to undo when the recursion returns. If you carry a list down instead (to record the path itself), you must remove the node on the way back up, or siblings will see each other's values.
Both at once: return one thing, record another
Some answers need a value returned up for the parent's use and a separate value tracked across the whole tree. The diameter (the longest path between any two nodes, counted in edges) is the standard case. Each node returns its height to its parent, and while it has both children's heights in hand, it checks whether the longest path through itself beats the best seen so far:
def diameter(root: Optional[TreeNode]) -> int:
best = 0
def height(node: Optional[TreeNode]) -> int:
nonlocal best
if node is None:
return 0
left = height(node.left)
right = height(node.right)
best = max(best, left + right) # longest path through this node
return 1 + max(left, right)
height(root)
return bestCheck the small cases out loud: an empty tree returns 0, a single node returns 0 (no edges), and a root with two leaf children returns 2. The mistake to avoid is returning left + right to the parent: the parent can only extend one branch of the path, never both.
BFS: level by level
A queue visits nodes in order of distance from the root. To group them by level, read the queue's length at the start of each round; exactly that many nodes belong to the current level.
def level_order(root: Optional[TreeNode]) -> list[list[int]]:
if root is None:
return []
levels: list[list[int]] = []
queue = deque([root])
while queue:
level: list[int] = []
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.val)
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
levels.append(level)
return levelsTime is O(n). Space is O(w), the widest level, which can be about n/2 in a full tree. Many variants are this function with a different line in the middle: the right side view keeps only the last value of each level, zigzag order reverses every other level, and "minimum depth" returns the level number of the first leaf it meets, which BFS finds before it explores anything deeper.
Binary search trees
In a binary search tree, every value in a node's left subtree is smaller than the node and every value in its right subtree is larger. Two consequences carry most BST questions:
An in-order traversal (left, node, right) visits values in sorted order. "Kth smallest" is the kth value of an in-order walk, and you can stop early.
Search, insert and delete take O(h), which is O(log n) only when the tree is balanced.
Validating a BST is the classic trap. Checking each node against its two children is not enough. In this tree, every parent-child pair looks right, yet 6 sits in the left subtree of 5:
5
/
3
\
6The fix is to carry the allowed range down:
def is_valid_bst(
node: Optional[TreeNode],
low: float = float("-inf"),
high: float = float("inf"),
) -> bool:
if node is None:
return True
if not (low < node.val < high):
return False
return is_valid_bst(node.left, low, node.val) and is_valid_bst(
node.right, node.val, high
)On the tree above, 6 is checked against the range (3, 5) and fails. The strict < assumes no duplicate values; ask the interviewer how duplicates are defined before you choose < or <=.
When recursion is too deep
Python's default recursion limit is 1,000 frames. A tree of 100,000 nodes that degenerates into a chain raises RecursionError in every recursive solution above. Interviewers sometimes ask about it directly. Raising the limit with sys.setrecursionlimit works on Python 3.11 and later, which no longer spend native stack on Python-to-Python calls, but on older versions, and in Java or C++, a recursion that deep overflows the native stack and kills the process. The answer that holds in every language is an explicit stack. Here is an iterative in-order traversal:
def inorder(root: Optional[TreeNode]) -> list[int]:
values: list[int] = []
stack: list[TreeNode] = []
node = root
while node is not None or stack:
while node is not None: # walk as far left as possible
stack.append(node)
node = node.left
node = stack.pop()
values.append(node.val)
node = node.right
return valuesTrace it on a root 2 with left child 1 and right child 3: push 2, push 1, pop 1 (record 1), its right is empty, pop 2 (record 2), move to 3, push 3, pop 3 (record 3). Output 1, 2, 3.
Pre-order is simpler iteratively: pop a node, record it, push the right child, then the left child so the left is processed first.
What the interviewer hears: weak and strong
Take the diameter. A weak attempt adds the left and right heights at the root only. On a root whose only child, 2, has two branches of two nodes each (3 then 4, and 5 then 6), it returns 3, but the longest path, 4-3-2-5-6, has 4 edges and never touches the root. The candidate then patches the code by trial and error. The code may end up working, but the report has no evidence of problem solving, and the debugging reads as luck.
A strong attempt sounds like this before any code: "The longest path passes through some highest node, and there it is the left height plus the right height. So height returns the height to the parent, and I record left + right at each node in a variable outside the recursion. Base case: an empty subtree has height 0. One visit per node, O(n) time, O(h) stack." Then the code, then three tests out loud: empty tree, single node, and a chain. That covers problem solving, communication, and testing and edge cases before the interviewer asks.
If you stall, the hint is usually a question about the contract: "What should height return for an empty subtree?" Answer it as a sentence, then fix the code from the sentence.
Follow-ups to expect
"What is the space complexity?" O(h) for DFS, O(w) for BFS. Say what h is for a balanced tree and for a chain.
"Can you do it without recursion?" An explicit stack for DFS, as above.
"What if the tree is a BST?" Look for a way to skip whole subtrees: searching for a value or a range only follows one side at each node.
"What if the nodes have parent pointers, or the tree is n-ary?" The patterns hold; loop over a list of children instead of two fields.
What changes with seniority
A junior candidate should get the base cases right and state O(n) time. A mid-level candidate states O(h) space, explains why the naive BST check fails, and tests a chain-shaped tree unprompted. A senior candidate picks between returning values and carrying state without trial and error, handles deep trees iteratively, and explains the cost when a BST is unbalanced.
Mistakes that cost points
No contract for the recursive function. If you cannot say what a call returns, the base case will be wrong. Write the sentence first.
Base case on
Nonewhen the rule is about leaves. Path questions need the leaf check on a real node.Returning the combined value to the parent. The diameter is recorded at the node; only the height goes up.
Mutable state carried down without undoing it. Append before recursing, pop after.
Validating a BST against children only. Carry the range.
Practice it
A 15-minute drill:
Write
sum_of_left_leaves(root)and decide first whether information flows up or down. (It needs both: the parent tells a child whether it is a left child.)Convert
level_orderinto a function that returns the right side view, changing as few lines as you can.Draw a five-node chain and trace
inorderon it by hand to confirm the stack never holds more than five nodes.
Then rehearse the same out-loud routine (contract, base case, complexity, three tests) in a full coding interview such as Two Sum.
Previous: Heaps and Top K. Next: Graphs, where the same traversals meet cycles and need a visited set.
Practise this in a mock interview
Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.
- Two SumCoding · Easy
- Design an LRU CacheCoding · Medium
- Deploy Services in Dependency WavesCoding · Medium
- Flag Overlapping Maintenance WindowsCoding · Medium
Read next
- Graphs
Model a problem as a graph and pick the right tool (BFS, DFS, topological sort, Dijkstra or union-find) while avoiding the visited-set and recursion-depth bugs that cost correctness points.
9 min read
- Backtracking: Searching Every Option Without Getting Lost
Spot 'list every answer' problems, apply one choose, explore, unchoose template to subsets, permutations, combinations and constraint puzzles, prune early, and state the exponential cost honestly.
9 min read
- Dynamic Programming: From Recursion to a Table
Recognize a dynamic programming problem, apply a five-step recipe (state, recurrence, base case, order, answer), move from memoization to a table and cut its space, and explain the solution out loud.
9 min read
- Intervals and Greedy: Sort First, Then Decide Once
Merge, insert and count overlapping intervals with a sort-then-sweep template, justify a greedy rule with the exchange argument, and recognize when greedy fails and dynamic programming is needed.
9 min read
