LeetcodeMay 14, 2025

Balanced Binary Tree

Hazrat Ali

Leetcode

Given a binary tree, determine if it is.

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


Solution
const isBalanced = root => {
  const getHeight = root => {
    if (!root) {
      return 0;
    }

    const leftHeight = getHeight(root.left);
    if (leftHeight < 0) {
      return -1;
    }

    const rightHeight = getHeight(root.right);
    if (rightHeight < 0) {
      return -1;
    }

    if (Math.abs(leftHeight - rightHeight) > 1) {
      return -1;
    }

    return 1 + Math.max(leftHeight, rightHeight);
  };

  return getHeight(root) >= 0;
};


Comments