← All topics

Trees

Recursion's home turf. Most tree problems are a DFS or BFS with a small twist, and the recursive solution is usually shorter and clearer than the iterative one -- trust the recursion to handle the subtrees correctly.

226. Invert Binary Tree

Given the root of a binary tree, invert it (swap every left/right child) and return the root.

def invert_tree(root):
    if not root:
        return None
    root.left, root.right = (
        invert_tree(root.right),
        invert_tree(root.left),
    )
    return root

Trust that invert_tree already correctly inverts whatever subtree you hand it, then the only work left at this node is swapping its two children. The base case -- an empty subtree inverts to itself -- stops the recursion.

104. Maximum Depth of Binary Tree

Given the root of a binary tree, return its maximum depth (longest path from root to a leaf).

def max_depth(root):
    if not root:
        return 0
    return 1 + max(max_depth(root.left), max_depth(root.right))

The depth of a tree is one more than the deeper of its two subtrees' depths -- the recursive definition translates almost word for word into code.

Same topic, no training wheels. Solve these on your own before you check the editorial.