Skip to content
DSAPrep

    ↑↓ to move · Enter to open · Esc to close

    ← All patterns

    Trees

    Recursion that combines answers from the left and right subtrees.

    Reach for it when

    • Binary tree / BST input
    • Depth, diameter, path sums, balance, ancestors
    • Level-by-level output (BFS)

    Core idea

    Most tree problems are a post-order DFS: ask each child for a summary, combine the two summaries at the node, and return a summary to the parent. If the answer may not pass through the root, update a global best while returning a different value upward. BSTs add an ordering invariant that in-order traversal visits in sorted order.

    Template · O(n) time, O(h) recursion stack

    def diameter(root):
    best = 0
    def depth(node):
    nonlocal best
    if not node:
    return 0
    l, r = depth(node.left), depth(node.right)
    best = max(best, l + r) # path bending at node
    return 1 + max(l, r) # path continuing upward
    depth(root)
    return best

    Common pitfalls

    • Confusing what you return upward with what you record globally
    • BST validation needs (low, high) bounds, not just parent comparisons
    • Deep skewed trees can hit the recursion limit: use an explicit stack

    Practice · 0 / 18 done