TRT
Sign in
easyCoreLeetCode#bottom-up recursion#sentinel value

Balanced binary tree

Decide whether every node's subtrees differ in height by at most one, in a single O(n) pass.

The Runtime Theory Team1 min read
Taught inTree recursion patternsPro — members onlyMost tree problems are solved by one of three recursive shapes: combine the children's answers on the way up, pass information down from the root, or return one value while updating a global best.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inroot = [3, 9, 20, null, null, 15, 7]

outtrue

inroot = [1, 2, 2, 3, 3, null, null, 4, 4]

outfalse

inroot = []

outtrue

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

  1. Return the subtree's height, or -1 if it is unbalanced.
  2. If either child returns -1, or their heights differ by more than 1, return -1.
  3. 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.

Not started

Sign in to save your learning progress.

Sign in to save