Given a binary tree, return whether it is height-balanced: for every node, the heights of its two subtrees differ by at most one.
Before you code
Computing heights separately at every node repeats work and costs up to O(n²). Compute height and balance together, bottom-up, in one pass.
Hints
- Return the subtree's height, or -1 if it is unbalanced.
- If either child returns -1, or their heights differ by more than 1, return -1.
- Otherwise return
1 + max(left, right).
Production & complexity notes
When solving Balanced binary tree on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Tree recursion patterns to reinforce the underlying pattern.
What it practices
Avoiding repeated work in bottom-up recursion, from Tree recursion patterns.