CodingNodes / Trees / Balanced Binary Tree System design Space play · ←→ step · R restart

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.

The tree is given in level order, with null for a missing child. An empty tree is balanced.

Constraints

  • 0 ≤ number of nodes ≤ 5000
  • -10000 ≤ Node.val ≤ 10000

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(h)

Time: Every node is visited once, and each visit does constant work after its children return.

Space: The recursion goes as deep as the tree is tall, h. That is log n for a balanced tree and n for a chain.

Compute heights from the bottom up, and let the same call report trouble. If a child returns -1, or the two heights differ by more than 1, return -1. Otherwise return 1 plus the larger height. The tree is balanced exactly when the root does not return -1.