0:00 / 0:00

Is every node's left and right height within one? Return each subtree's height from the bottom up, and a -1 the moment any node is lopsided.

▼

The problem

LeetCode 110 (Easy). Given the root of a binary tree, return true if it is height-balanced: at every node, the heights of the left and right subtrees differ by at most one.

Examples (LeetCode's): [3,9,20,null,null,15,7] → true, [1,2,2,3,3,null,null,4,4] → false (the root's left side is 3 tall, its right side 1).

TRY IT ON LEETCODE ▶

The solution

def is_balanced(root):
    def height(node):
        if not node:
            return 0
        left = height(node.left)
        if left == -1:
            return -1
        right = height(node.right)
        if right == -1 or abs(left - right) > 1:
            return -1
        return 1 + max(left, right)
    return height(root) != -1

Transcript

Balanced Binary Tree. Given the root of a binary tree, return true if it's height balanced. That means at every node, the left and right subtrees differ in height by at most one. Every node, not just the root.

Take three, nine, twenty, with fifteen and seven under twenty. Nine's side is one tall and twenty's is two: they differ by one, and every node below is level, so it's true. In the second tree, the root's left side is three tall, its right just one. They differ by two: false.

The direct way: at every node, measure both subtrees from scratch. But each measurement walks everything below, so a deep node gets walked again for every ancestor. On this tall tree of six nodes, that's fifteen steps. As trees grow, it heads toward n squared.

The fix: measure once, from the bottom up. Each call returns its height, so a parent gets both heights for free and just compares them. If anything below is unbalanced, return minus one instead. That minus one passes straight up, and the rest of the tree is never visited.

In code, a helper returns the height. An empty node has height zero. If the left height is minus one, pass it up. If the right is minus one, or the two differ by more than one, return minus one. Otherwise, return one plus the taller side. The tree is balanced if the root's height isn't minus one.

Let's run three, nine, twenty. Nine is a leaf, with two empty children: height one. Twenty asks fifteen and seven, and each says one. One and one are level, so twenty is two. Back at the root, one and two differ by just one: fine. Height three, not minus one: true.

Each node is visited once, with constant work, so the time is order n. The recursion goes as deep as the tree is tall, so the stack takes order h space.

Return heights, flag minus one, stop early. That's Balanced Binary Tree.