Balanced Binary Tree - Problem

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

A height-balanced binary tree is defined as: a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

The height of a tree is the number of edges in the longest path from the root to a leaf node. An empty tree has height -1.

Input & Output

Example 1 — Balanced Tree
$ Input: root = [3,9,20,null,null,15,7]
Output: true
💡 Note: Height of left subtree (9) is 0, height of right subtree (20) is 1. Difference is 1 ≤ 1, so balanced. All other nodes are also balanced.
Example 2 — Unbalanced Tree
$ Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
💡 Note: The left subtree has height 3 while right subtree has height 0. Difference is 3 > 1, making it unbalanced.
Example 3 — Empty Tree
$ Input: root = []
Output: true
💡 Note: An empty tree is considered balanced by definition.

Constraints

  • The number of nodes in the tree is in the range [0, 5000]
  • -104 ≤ Node.val ≤ 104

Visualization

Tap to expand
Balanced Binary Tree - Optimized DFS INPUT Binary Tree Structure: 3 9 20 15 7 Input Array: [3,9,20,null,null,15,7] Height = edges to deepest leaf Empty tree height = -1 ALGORITHM STEPS 1 Base Case Empty node returns -1 2 Recursive DFS Get left & right heights 3 Check Balance |leftH - rightH| <= 1 4 Return Height max(leftH,rightH) + 1 Height Calculation: Node 9: h=0 (leaf) Node 15: h=0 (leaf) Node 7: h=0 (leaf) Node 20: h=max(0,0)+1=1 Node 3: h=max(0,1)+1=2 |0-1|=1 <= 1 [OK] FINAL RESULT Balanced Tree Verified: 3 h=2 9 h=0 20 h=1 15 7 At node 3: |0-1| = 1 [OK] At node 20: |0-0| = 0 [OK] Output: true Tree is height-balanced! Key Insight: Single-pass DFS computes height AND checks balance simultaneously. Return -2 to signal imbalance early, avoiding redundant traversals. Time: O(n), Space: O(h) where h = tree height. TutorialsPoint - Balanced Binary Tree | Optimized DFS - Single Pass
Asked in
Amazon 15 Google 12 Microsoft 8 Facebook 6
832.0K Views
Medium Frequency
~15 min Avg. Time
7.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen