Given a binary tree, determine if it is height-balanced: for every node, the heights of its two subtrees differ by at most one.
Return each subtree's height from a post-order DFS, or −1 as soon as any subtree is unbalanced. Each node is visited once.
1function isBalanced(root: TreeNode | null): boolean {2function check(n: TreeNode | null): number {3if (!n) return 0;4const l = check(n.left);5const r = check(n.right);6if (l === -1 || r === -1 || Math.abs(l - r) > 1) return -1;7return 1 + Math.max(l, r);8}9return check(root) !== -1;10}
At 1: check the left subtree.
Space: play/pause · ←/→: step