InterviewPrepKit

Home / Coding / Trees

Balanced Binary Tree

easy Original ↗
Solving tips
  • Avoid the O(n^2) trap of recomputing heights top-down at every node; compute height bottom-up and check balance in the same post-order pass.
  • Use a sentinel: have the recursion return the subtree height, or -1 the moment any subtree is unbalanced, so failure short-circuits straight up.
  • Propagate the -1 unchanged (check for it before computing 1 + max(left, right)), or the sentinel gets mistaken for a real height.
  • Remember balance must hold at every node, not just the root, and an empty tree is balanced; target O(n) time and O(h) space.

Problem

Given the root of a binary tree, decide whether it is height-balanced: at every node, the heights of the left and right subtrees differ by at most 1. Return True if the whole tree satisfies this, False otherwise. An empty tree counts as balanced.

Note the condition must hold at every node, not just the root — a tree can look balanced from the top while hiding a lopsided subtree deeper down.

Examples

Example 1

Input:  root = [3,9,20,null,null,15,7]

        3
       / \
      9  20
        /  \
       15   7

Output: True

At every node the left/right heights differ by at most 1.

Example 2

Input:  root = [1,2,2,3,3,null,null,4,4]

            1
           / \
          2   2
         / \
        3   3
       / \
      4   4

Output: False

At the left child 2, the left subtree has height 2 but the right subtree has height 1 below it — and at the root, left height 3 vs right height 1 breaks the rule.

Example 3

Input:  root = []
Output: True

An empty tree is balanced by definition.

Constraints

  • The number of nodes is in [0, 5000] — O(n) is expected; O(n^2) squeaks by but is the “brute force” an interviewer will ask you to beat.
  • -10^4 <= Node.val <= 10^4 — values are irrelevant; only the shape matters.

Think about it first

Hint 1 You already know how to compute the height of a tree recursively. Balance at a node is a statement about two heights.
Hint 2 Checking balance at every node by recomputing heights repeats work: the height of a node is recomputed once for each of its ancestors. Can one traversal answer both questions at once?
Hint 3 Do a post-order DFS that returns the subtree height, but return a sentinel like `-1` the moment any subtree is unbalanced — the failure bubbles straight up without further work.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.