mediumTreeTrees

Diameter of Binary Tree

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

Recognize the pattern

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

Brute force idea

If you approach Diameter of Binary Tree in the most literal way possible, you get this: 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.

Better approach

The real unlock in Diameter of Binary Tree comes when you notice this: 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.

Key invariant

The compass for Diameter of Binary Tree is this: 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.

Watch out for

One easy way to drift off course in Diameter of Binary Tree is this: 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