AlgoInsight

DSA problem

Balanced Binary Tree

EasyTree Traversal - Post-OrderPattern: Tree Traversal - Post-Ordertop600AmazonGoogleMicrosoftBloombergApple

Given the root of a binary tree, determine if it is height-balanced. A binary tree is height-balanced if, for every node in the tree, the heights of its two child subtrees differ by no more than 1. An empty tree is height-balanced by definition.

A naive solution computes the height of every subtree by recursion, then re-walks the tree comparing left and right heights at each node. That approach is correct but costs O(n²) time in the worst case (a skewed tree), because the height function is invoked on every node and each call can itself walk a path of length O(n).

The optimal post-order approach computes height and balance simultaneously in a single pass. As the recursion unwinds, each call returns the height of the subtree rooted at that node — unless the subtree is unbalanced, in which case it returns a sentinel value of -1 to short-circuit the entire traversal. A node propagates -1 upward immediately if either child reported -1 or if the heights of its two children differ by more than 1.

Because every node is visited exactly once and performs constant work, the algorithm runs in O(n) time and uses O(h) call-stack space. The sentinel pattern is a classic post-order technique: collapse multiple pieces of information (height + validity) into a single return value so the recursion does not need extra parameters or shared state.

Examples

Example 1
Input: root = [3,9,20,null,null,15,7]
Output: true
Explanation: Every node has left/right subtree heights differing by at most 1, so the tree is balanced.
Example 2
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
Explanation: The left subtree rooted at the first 2 has height 3 while the right subtree has height 1; their difference exceeds 1, so the tree is unbalanced.
Example 3
Input: root = []
Output: true
Explanation: An empty tree is balanced by definition.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

treebinary-treedepth-first-searchrecursion

Browse all DSA problems