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
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
| Question | Compare |
|---|---|
| same tree | a.left with b.left, a.right with b.right |
| mirror / symmetric | a.left with b.right, a.right with b.left |
| isomorphic | either 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
- Maximum Depth of Binary Treeeasyguide ready
- Same Treeeasyguide ready
- Balanced Binary Treeeasyguide ready
- Diameter of Binary Treeeasyguide ready
- Symmetric Treeeasyguide ready
- Count Complete Tree Nodesmediumguide ready
- Mirror of a treemediumguide ready
- Check if all leaf nodes are at same level or notmediumguide ready
- Check if 2 trees are mirror or notmediumguide ready
- Tree Isomorphism Problemmediumguide ready