Binary Tree

Balanced Tree Visualizer

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.

HeightThe height of a missing child is 0. A node's height is 1 plus the taller child.
The checkIf the two heights differ by 2 or more, this node fails the test even when its children were balanced.

The picture labels each node with the height it returns. A failing node is the one highlighted when the answer becomes no.

Interactive solution

Heights written on the way back up
def height(node):
if node is null: return 0
left = height(node.left)
right = height(node.right)
if left < 0 or right < 0: return -1
if abs(left - right) > 1: return -1
return 1 + max(left, right)
Step 0/0 Answer —

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

PieceCostWhy
TimeO(n)One height is computed per node.
Call stackO(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)