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
Understanding the Visualization
1
Input Tree
Binary tree with nodes and structure
2
Height Check
Calculate heights and compare differences
3
Balance Result
Return true if all nodes satisfy balance condition
Key Takeaway
🎯 Key Insight: Check height difference at every node - if any exceeds 1, the tree is unbalanced
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code