Skip to content

Trees

Trees in under a minute

A binary tree is a node plus two smaller binary trees. That self-similarity is why most tree problems fall to a short recursive function, and why the rest fall to a queue.

  • The input is a binary tree (or a BST) given as a root node.
  • The answer for a node can be built from the answers for its left and right subtrees (depth, balance, path sums, “is this valid?”).
  • The problem talks about levels, “row by row” or “closest to the root”: use BFS.
  • The tree is a BST: an in-order walk is sorted, and every node has an allowed value range inherited from its ancestors.
  • Recursion depth is the tree height h: O(log n) if balanced, O(n) if skewed.
def dfs(node):
if node is None: # base case: the empty tree
return BASE
left = dfs(node.left) # trust the recursion: it answers for the subtree
right = dfs(node.right)
return combine(node, left, right)
def bfs(root): # one list per level
queue = deque([root] if root else [])
while queue:
for _ in range(len(queue)): # freeze the size: exactly one level
node = queue.popleft()
visit(node)
queue.extend(c for c in (node.left, node.right) if c)

For a BST, pass bounds down instead: dfs(node, low, high) and require low < node.val < high.