DSA AnimatorDSA animations
Balanced Binary Tree LC #110 Easy DFS · Sentinel -1
Problem

Given a binary tree, determine if it is height-balanced. A binary tree in which the left and right subtrees of every node differ in height by no more than 1.

Example 1
Input: root = [3,9,20,null,null,15,7]
Output: true
Explanation: Max height diff at any node is 1.
Example 2
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
Explanation: Left subtree depth 4, right depth 2 — diff = 2 > 1.
Example 3
Input: root = [1,2,3,4,5]
Output: true
Constraints: 0 ≤ number of nodes ≤ 5000  |  −104 ≤ Node.val ≤ 104
Try Examples
Custom:
Approach
DFS Post-order with Sentinel −1
height() returns actual height if subtree is balanced, or −1 as a sentinel for "unbalanced". A single O(n) pass — once −1 is returned, it propagates up immediately.
Binary Tree
Processing
Balanced ✓
Unbalanced ✗
Returning
Visited
Balance Checker — Current Node
Waiting for first node…
Height Return Table
NodeL.HR.H|diff|return
No rows yet…
Variables
Node
—
L height
—
R height
—
return
—
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Recursion Stack
Stack is empty — not started
Algorithm Steps
1
Base case: node == null → return 0 (null height is 0)
2
Recurse left: L = height(node.left) — if L == −1, propagate −1 immediately
3
Recurse right: R = height(node.right) — if R == −1, propagate −1 immediately
4
Check: |L − R| > 1 → this node is unbalanced, return −1
5
Return 1 + max(L, R) — the actual height of this balanced subtree
Time
O(n)
Space
O(h)
Why it Works

Using −1 as sentinel avoids a second pass. As soon as any subtree is unbalanced, all ancestor calls propagate −1 upward instantly — O(n) single-pass check. The recursion visits every node exactly once in post-order (children before parent), so when we check |L−R|, both subtree heights are already available. If the root receives a real height (≥ 0), the tree is balanced.

How to solve Balanced Binary Tree

LeetCode 110 · Easy · Tree · Pattern: DFS Height with Early Exit

Why the obvious approach is slow

You could compute the height of both subtrees at every node, from scratch. That repeats the same height work again and again, which is O(n²) on a chain. Instead, compute heights bottom up, just once.

The key idea

Write a height function that also checks the balance as it goes. It returns the real height when the subtree is balanced. It returns −1 as a signal when it finds any imbalance. Once a child returns −1, pass −1 straight up without more work. The tree is balanced if the root does not return −1.

Remember

Return the height, and use −1 as an error signal. Bottom up turns O(n²) into O(n).

Run the animation above on your own input, or watch the 2:07 video explanation of Balanced Binary Tree with a dry run and Java code.

More Tree problems