← DSA
EASY

Balanced Binary Tree

PracticeNeetCode ↗LeetCode ↗

Given a binary tree, determine if it is height-balanced: for every node, the height difference between its left and right subtrees is at most 1.

Example

Input root = [3,9,20,null,null,15,7]
Output true

Key Pointers

Step-by-Step Analysis

  1. Define height(node); base case None returns 0.
  2. Recursively compute the left height; if it's -1, return -1 immediately.
  3. Recursively compute the right height; if it's -1, return -1 immediately.
  4. If abs(left - right) > 1, return -1; otherwise return 1 + max(left, right).
  5. The tree is balanced iff height(root) != -1.

Complexity

Time: O(n) — Space: O(h)

Code

def isBalanced(root: TreeNode | None) -> bool:
    def height(node: TreeNode | None) -> int:
        if not node:
            return 0
        left = height(node.left)
        if left == -1:
            return -1
        right = height(node.right)
        if right == -1:
            return -1
        if abs(left - right) > 1:
            return -1
        return 1 + max(left, right)

    return height(root) != -1

Code Explanation

How the solution above works, piece by piece.

  1. height returns the subtree height, or −1 as a special value meaning "unbalanced somewhere below".
  2. Compute the left height; if it's −1, stop immediately and pass −1 up. Same for the right.
  3. If the two heights differ by more than 1, this node is unbalanced: return −1.
  4. Otherwise return the normal height 1 + max(left, right).
  5. Checking and measuring in the same pass makes it O(n); calling a separate height function at every node would be O(n²).

Visual Walkthrough

Running it on root = [3, 9, 20, null, null, 15, 7]:

Heights used for the balance check392015731211badge = heightat 20: |1 − 1| = 0 ✓at 3: |1 − 2| = 1 ✓no node differs by > 1 → True
Each node compares its two children's heights. A difference above 1 anywhere would return −1, which the code uses as an "unbalanced" signal that is passed straight up without further work.

Video Explanation

NeetCode — Balanced Binary Tree, LeetCode 110