SDE & MLE Prep

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