AAlgoLoopSpaced repetition for LeetCode
EASYTree / RecursionLeetCode ↗

Balanced Binary Tree

The key idea

Compute each node's height in a single bottom-up pass and check balance on the way up. Return a sentinel -1 the moment any subtree is unbalanced so the recursion short-circuits instead of recomputing heights from the top down.

Problem

Given a binary tree, determine if it is height-balanced.

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than 1.

Return true if the tree rooted at root is height-balanced, and false otherwise. An empty tree is considered balanced.

Constraints

Examples

Input: root = [3,9,20,null,null,15,7] Output: true
Input: root = [1,2,2,3,3,null,null,4,4] Output: false
Input: root = [] Output: true

Complexity

Time: O(n) Space: O(h)

See the full solution

410310
Step-by-step visualization
Start free →

More Tree / Recursion problems