Trees Pattern Hub
11 problemsBalanced Binary Tree
easyEncode 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
mediumStandard 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
hardPost-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
easyIn 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
easyAt 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
mediumIterative 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
mediumWalk 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
easyPost-order recurrence: an empty tree has depth `0`; otherwise `1 + max(maxDepth(left), maxDepth(right))`.
Same Tree
easyBase cases first: both null => `True`; one null => `False`; values differ => `False`. Otherwise recursively verify left and right child equality.
Subtree of Another Tree
easyA 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
mediumPropagate 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`.