Home / Patterns / Trees

Trees Pattern Hub

11 problems

Balanced Binary Tree

easy
TC: O(N) · SC: O(H)

Encode imbalance with sentinel `-1` in a bottom-up height DFS: if either subtree returns `-1` or `abs(lh - rh) > 1`, immediately bubble `-1` upward without extra top-down scans.

Binary Tree Level Order Traversal

medium
TC: O(N) · SC: O(W)

Standard FIFO BFS queue: snapshot `qLen = len(q)` at the start of every outer loop iteration so the inner loop consumes strictly one depth level.

Binary Tree Maximum Path Sum

hard
TC: O(N) · SC: O(H)

Post-order DFS computes the maximum downward *single-branch* gain (`max(0, dfs(child))` — clamp negatives to `0`). At each node `u`, evaluate splitting through `u` (`u.val + leftGain + rightGain`) against the global max, then return `u.val + max(leftGain, rightGain)` upward.

Diameter of Binary Tree

easy
TC: O(N) · SC: O(H)

In a single bottom-up DFS returning height, any node `u` can serve as the highest turning point of a path of edge length `leftH + rightH`. Maintain `best = max(best, leftH + rightH)` globally while returning `1 + max(leftH, rightH)` upward.

Invert Binary Tree

easy
TC: O(N) · SC: O(H)

At every node, swap `left` and `right` children, then recursively invert both subtrees (pre-order, post-order, or BFS queue all preserve the mirror invariant).

Kth Smallest Element in a BST

medium
TC: O(H + k) · SC: O(H)

Iterative inorder traversal using an explicit stack stops immediately on the `k`-th pop—visiting only `O(H + k)` nodes instead of traversing the entire tree.

Lowest Common Ancestor of a Binary Search Tree

medium
TC: O(H) · SC: O(1)

Walk down from `root` iteratively using the BST ordering property: if both `p.val` and `q.val` are strictly less than `curr.val`, go left; if both strictly greater, go right; otherwise `curr` is the split point (LCA).

Maximum Depth of Binary Tree

easy
TC: O(N) · SC: O(H)

Post-order recurrence: an empty tree has depth `0`; otherwise `1 + max(maxDepth(left), maxDepth(right))`.

Same Tree

easy
TC: O(min(P, Q)) · SC: O(min(Hp, Hq))

Base cases first: both null => `True`; one null => `False`; values differ => `False`. Otherwise recursively verify left and right child equality.

Subtree of Another Tree

easy
TC: O(S * T) · SC: O(Hs)

A tree rooted at `root` contains `subRoot` iff `sameTree(root, subRoot)` or `subRoot` is in `root.left` or `root.right`. (For huge trees, serialize preorder with null sentinels + `#` delimiter and run KMP in `O(S + T)`.)

Validate Binary Search Tree

medium
TC: O(N) · SC: O(H)

Propagate an open validity interval `(lo, hi)` down the recursion: moving left narrows upper bound to `node.val`, moving right narrows lower bound to `node.val`. Strictly enforce `lo < node.val < hi`.