Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created February 8, 2026 19:54
Show Gist options
  • Select an option

  • Save tatsuyax25/63f6d221307255ed19b134c92bebdc54 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/63f6d221307255ed19b134c92bebdc54 to your computer and use it in GitHub Desktop.
Given a binary tree, determine if it is height-balanced.
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
// Determine whether a binary tree is height-balanced.
// A tree is balanced if, at every node, the heights of the left and right
// subtrees differ by no more than 1.
var isBalanced = function(root) {
// If getHeight returns -1, the tree is unbalanced.
return getHeight(root) !== -1;
/**
* Recursively compute the height of a subtree.
* Returns:
* - a non-negative integer = height of the subtree
* - -1 if the subtree is already known to be unbalanced
*/
function getHeight(node) {
// An empty subtree has height 0.
if (!node) {
return 0;
}
// Recursively compute heights of left and right subtrees.
const leftHeight = getHeight(node.left);
const rightHeight = getHeight(node.right);
// If either subtree is unbalanced, or the height difference is > 1,
// propagate the failure upward by returning -1.
if (
leftHeight === -1 ||
rightHeight === -1 ||
Math.abs(leftHeight - rightHeight) > 1
) {
return -1;
}
// Otherwise, return the height of this subtree.
return 1 + Math.max(leftHeight, rightHeight);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment