InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Balanced Binary Tree

easy Original ↗ 00:00

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.

The condition must hold at every node, not just the root. A tree can be balanced at the root while an unbalanced subtree hides 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) passes but is the brute force an interviewer will ask you to beat.
  • -10^4 <= Node.val <= 10^4. Values do not matter; only the tree’s shape does.

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` as soon as any subtree is unbalanced. The failure propagates straight up without further work.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug