← Tree Recursion

Pattern Recognition Drill

#139 — Diameter of Binary Tree

Easy Trees

The Problem

Find the diameter (longest path between any two nodes) of a binary tree.

What approach would you use?

Think about it before scrolling down.

Key Signals

Tree Recursion

Post-order: return height. At each node, update diameter = max(diameter, left_h + right_h). O(n).

Alt: DFS / Recursion

Same approach. The diameter is a side effect of computing heights.

Common Trap

Diameter is NOT always through the root. It can be entirely in a subtree.

← #138