mediumTreeTrees

Diameter of Binary Tree

mediumTime: O(n)Space: O(h)

Signals to notice

longest path through any nodepath doesn't need to go through rootcombine left and right depths

Brute force first

For each node, compute depths of both subtrees — because depth computation is and you repeat for every node. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

DFS returning depth, but at each node also compute the diameter THROUGH that node (left depth + right depth). Track the global maximum. — one pass. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

What must stay true

The diameter through any node = leftDepth + rightDepth. The overall diameter is the maximum across all nodes. Each DFS call returns depth (for its parent) while also checking diameter (for the global answer). As long as that statement keeps holding, you can trust the steps built on top of it.

Easy way to go wrong

Only checking the diameter through the root — the longest path might not pass through the root at all. You must check every node. The fix is usually to return to the meaning of each move, not just the steps themselves.

Trees Pattern