Trees
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.
When to reach for it
Section titled “When to reach for it”- 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.
Template
Section titled “Template”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.
Problems in this guide
Section titled “Problems in this guide”- Invert Binary Tree — swap children at every node, recursively
- Maximum Depth of Binary Tree — one plus the deeper subtree
- Binary Tree Level Order Traversal — BFS with a queue, one level per pass
- Validate Binary Search Tree — pass allowed value bounds down the tree
- Lowest Common Ancestor of a Binary Tree — first node with a target on each side
- Serialize and Deserialize Binary Tree — preorder with null markers round-trips