Learn / Trees

Depth, diameter and balance

Many tree questions are answered by one post-order function that returns something about each subtree: its height, whether it matches another tree, the longest path through it. The answer for a node is built from its children's answers, so the whole tree costs O(n).

How to recognise it

  • Height, depth, balance or diameter.
  • Comparing two trees, or a tree with its own mirror.
  • The answer for a node depends only on its two subtrees.

One function, two answers

12345
The diameter here is 3 edges: 4 to 2 to 1 to 3 (5 to 2 to 1 to 3 is as long). It bends at node 1.
height(n):
    if n is null: return 0
    l = height(n.left); r = height(n.right)
    best = max(best, l + r)        # the longest path bending at n (diameter)
    return 1 + max(l, r)

The function returns what its parent needs (the height) and records on the side what the question asks (the diameter). The same shape answers balance (return -1 once a subtree is unbalanced) and many others.

What a node, a child, a leaf and a level are is on the Structures page.

Comparing trees

QuestionCompare
same treea.left with b.left, a.right with b.right
mirror / symmetrica.left with b.right, a.right with b.left
isomorphiceither of the two pairings

Counting a complete tree fast

In a complete tree, if the leftmost and rightmost depths match, the tree is perfect and has 2^h - 1 nodes. Otherwise recurse; one side is always perfect, so this takes O(log² n).

Common mistakes

  • Computing the height again inside every call, which makes balance O(n²).
  • Counting the diameter in nodes when the question wants edges.

Problems

0 of 10 solved

Check yourself

A tree is balanced when?

The diameter is measured in?

Why does Balanced Binary Tree return -1 from the height function?

Two trees are mirrors when?