THN Interview Prep

110. Balanced Binary Tree

At a Glance

  • Topic: Binary Tree
  • Pattern: DFS
  • Difficulty: Easy
  • LeetCode: 110

Problem Statement

Given a binary tree, determine if it is height-balanced.

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].
-104 <= Node.val <= 104

Approach & Solution Steps

Use a recursive DFS approach to calculate the height of each subtree. If a subtree is unbalanced or the height difference exceeds 1, return -1 to indicate it's unbalanced.

Optimal JS Solution

function isBalanced(root) {
  const dfs = (node) => {
    if (!node) return 0;
    const left = dfs(node.left);
    const right = dfs(node.right);
    if (left === -1 || right === -1 || Math.abs(left - right) > 1) return -1;
    return 1 + Math.max(left, right);
  };
  return dfs(root) !== -1;
}

Edge Cases & Pitfalls

  • Always consider empty or null inputs.
  • Watch out for off-by-one index errors.

Mark this page when you finish learning it.

Last updated on

Spotted something unclear or wrong on this page?

On this page