Balanced Binary Tree Problem
Description
LeetCode Problem 110.
Given a binary tree, determine if it is height-balanced. For this problem, 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.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: true
Example 2:
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
Example 3:
Input: root = []
Output: true
Constraints:
- The number of nodes in the tree is in the range [0, 5000].
- -10^4 <= Node.val <= 10^4
Solution
Approach: Bottom-Up Height Check
The direct way is to compute the height of both subtrees at every node and compare them. But computing a height visits the whole subtree, so doing it again at every node costs O(n2) for a tree shaped like a list.
Instead, compute heights bottom-up and check balance on the way. A recursive function height(node) returns the height of the subtree, or a special value UNBALANCED (-1, which no real height can be) as soon as it finds an unbalanced node anywhere below:
- An empty subtree has height 0.
- Compute
left = height(node.left). If it isUNBALANCED, returnUNBALANCEDright away. - Do the same for
right. - If
|left - right| > 1, this node is unbalanced: returnUNBALANCED. - Otherwise return
1 + max(left, right).
The tree is balanced exactly when height(root) is not UNBALANCED.
Each node computes its height once from its children's results, so nothing is recomputed. The early returns also stop the walk at the first unbalanced subtree.
Note that balance must hold at every node, not just the root. In [1,2,2,3,null,null,3,4,null,null,4] both subtrees of the root have height 3, yet the tree is not balanced, because each node 2 has subtrees of heights 2 and 0.
Complexity: O(n) time, where n is the number of nodes, since each node is visited once. O(h) space for the recursion stack, where h is the height of the tree.
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
UNBALANCED = -1 # returned instead of a height once some subtree is unbalanced
def height(node: Optional[TreeNode]) -> int:
"""Height of the subtree, or UNBALANCED."""
if node is None:
return 0
left = height(node.left)
if left == UNBALANCED:
return UNBALANCED
right = height(node.right)
if right == UNBALANCED:
return UNBALANCED
if abs(left - right) > 1:
return UNBALANCED
return 1 + max(left, right)
return height(root) != UNBALANCED