Created
February 8, 2026 19:54
-
-
Save tatsuyax25/63f6d221307255ed19b134c92bebdc54 to your computer and use it in GitHub Desktop.
Given a binary tree, determine if it is height-balanced.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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