What is Balanced Tree
A tree is height-balanced when every node, not only the root, has left and right heights that differ by at most one.
1 2 3 yes 1 2 -1 3 no
Approach
Compute the height from the leaves upward. At each node, compare the two heights before you return. If any node is already unbalanced, pass that failure upward.
The picture labels each node with the height it returns. A failing node is the one highlighted when the answer becomes no.
Interactive solution
The finished tree is on screen when the page opens. Next and Play start again from the first step. The play controls sit under the tree and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | One height is computed per node. |
| Call stack | O(h) | The walk is as deep as the tree. |
Implementation
def height(node):
if not node:
return 0
left, right = height(node.left), height(node.right)
if left < 0 or right < 0 or abs(left - right) > 1:
return -1
return 1 + max(left, right)