34 / 75
E

Diameter of Binary Tree

#34
treedfsrecursion

Track max diameter as sum of left and right heights at each node during DFS.

Example:

Input:root=[1,2,3,4,5]
Output:3 (path: 4->2->1->3 has 3 edges)

Common Mistakes:

  • Assuming diameter must pass through root (it doesn't)
  • Returning heights instead of diameter
  • Forgetting to track global max across all nodes
  • Counting nodes instead of edges (diameter is edge count)

Notes:

Classic tree problem. Diameter at node = left height + right height. Time O(n), Space O(h).

34/75
Diameter of Binary Tree