Example 1
- Input
- root = [3,9,20,null,null,15,7]
- Output
- true
Leaves 9, 15 and 7 have child heights 0 and 0. Node 20 has child heights 1 and 1; root 3 has child heights 1 and 2. Every gap is at most 1, so the whole tree is balanced.
Given the root of a binary tree, decide whether it is height-balanced, meaning the left and right subtrees of every node differ in height by at most one.
Given the root of a binary tree, determine whether the tree is height-balanced.
A tree is height-balanced when, for every node, the heights of its left and right subtrees differ by no more than 1. An empty tree counts as balanced.
Leaves 9, 15 and 7 have child heights 0 and 0. Node 20 has child heights 1 and 1; root 3 has child heights 1 and 2. Every gap is at most 1, so the whole tree is balanced.
The leaves 4 and 4 make their parent 3 height 2. Node 2 on the left has subtree height 3, whereas the right node 2 has height 1. Root 1 has a gap of 2 and fails the rule.
There are no nodes that can violate the height rule. The height helper returns 0 for an empty subtree and the verdict is true.
The root has equal subtree heights of 3, but each child 2 has heights 2 and 0. Those internal gaps of 2 make the tree unbalanced despite a passing root comparison.
Root 1 has heights 1 and 0, so a difference of exactly 1 is allowed. The leaf 2 is also balanced.
Height counts nodes on the longest downward path, with an empty subtree having height 0. Balance is a local rule that must hold everywhere: in Example 1, node 20 combines heights 1 and 1, then root 3 compares heights 1 and 2. Equal heights at the root alone cannot certify its descendants. A subtree can therefore return either its height or a signal that a lower node has already failed.
Reveal Top Down Height Check: intuition, complexity, and code
-1 for an imbalanced subtree and propagate it upward at once to skip the remaining work.true without any height comparison.-1 as an ordinary height or overwriting the sentinel before returning it.When a tree verdict needs subtree data, return the data and the verdict together bottom-up instead of remeasuring top-down.