Given a binary tree, determine if it is height-balanced. A binary tree is height-balanced if for every node, the heights of its left and right subtrees differ by at most one.
Output: true
Explanation: Heights: left subtree = 1, right subtree = 2. |1-2| = 1 ≤ 1. All subtrees similarly satisfy the condition.
Output: false
Explanation: The left subtree of root has height 3 while the right has height 1. |3-1| = 2 > 1.
Constraints:
0 <= Number of nodes <= 5000 -104 <= Node.val <= 104
Contents
Solution — Bottom-Up DFS (O(n)) Complexity Analysis
A naive top-down approach computes height repeatedly for the same subtrees — O(n log n) for
balanced, O(n2) for skewed. The optimal approach is a single bottom-up DFS pass that
simultaneously computes height and checks balance, using the sentinel value
Algorithm:
- If the node is null, return height 0.
- Recursively get the height of the left subtree; if it returns -1, propagate -1 upward.
- Recursively get the height of the right subtree; if it returns -1, propagate -1 upward.
- If
|leftHeight - rightHeight| > 1 , return -1 (imbalanced signal). - Otherwise return
1 + Math.max(leftHeight, rightHeight) .
- Time: O(n) — each node is visited exactly once in the bottom-up DFS.
- Space: O(h) — recursion stack depth equals the tree height h (O(log n) balanced, O(n) skewed).