110. Balanced Binary Tree
Problem
Decide whether a binary tree is height-balanced: at every node, the heights of the left and right subtrees differ by at most 1.
Example: [3,9,20,null,null,15,7] → true; [1,2,2,3,3,null,null,4,4] → false
Return height, or -1 as soon as any subtree is unbalanced (children heights differ by > 1). Single pass, O(n).
Complexity: O(n).
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def h(node):
if not node:
return 0
l, r = h(node.left), h(node.right)
if l < 0 or r < 0 or abs(l - r) > 1:
return -1
return 1 + max(l, r)
return h(root) >= 0
assert Solution().isBalanced(make_tree([3, 9, 20, None, None, 15, 7])) is True
assert Solution().isBalanced(make_tree([1, 2, 2, 3, 3, None, None, 4, 4])) is False
class Solution {
public boolean isBalanced(TreeNode root) { return h(root) >= 0; }
private int h(TreeNode n) {
if (n == null) return 0;
int l = h(n.left), r = h(n.right);
if (l < 0 || r < 0 || Math.abs(l - r) > 1) return -1;
return 1 + Math.max(l, r);
}
}
func isBalanced(root *TreeNode) bool {
var h func(*TreeNode) int // height, or -1 if unbalanced
h = func(node *TreeNode) int {
if node == nil {
return 0
}
l, r := h(node.Left), h(node.Right)
if l < 0 || r < 0 || l-r > 1 || r-l > 1 {
return -1
}
return 1 + max(l, r)
}
return h(root) >= 0
}