Balanced Binary Tree
Difficulty: Easy · Pattern: Trees & BST · LeetCode #110
Given a binary tree, determine whether it is height-balanced: for every node, the heights of its left and right subtrees differ by at most 1.
Examples
text
[3,9,20,null,null,15,7] → true
[1,2,2,3,3,null,null,4,4] → false
[] → trueHints
- The naive way calls
height()at every node, which costs O(n²) on a skewed tree. - Can one post-order pass return the height and report imbalance at the same time?
Approach
Use post-order DFS that returns the height, with -1 as a sentinel meaning "already unbalanced":
text
h(node):
if node is null: return 0
L = h(left); if L == -1: return -1
R = h(right); if R == -1: return -1
if |L - R| > 1: return -1
return 1 + max(L, R)Every node is visited once. As soon as one subtree is unbalanced, the -1 propagates straight to the top. This return a value plus a failure flag trick appears again in Diameter and Max Path Sum.
Complexity
Time: O(n). Space: O(h).
Python solution
def isBalanced(root):
def h(node):
if not node:
return 0
L = h(node.left)
if L < 0:
return -1
R = h(node.right)
if R < 0 or abs(L - R) > 1:
return -1
return 1 + max(L, R)
return h(root) >= 0JavaScript solution
function isBalanced(root) {
const h = (node) => {
if (!node) return 0;
const L = h(node.left);
if (L < 0) return -1;
const R = h(node.right);
if (R < 0 || Math.abs(L - R) > 1) return -1;
return 1 + Math.max(L, R);
};
return h(root) >= 0;
}