34 / 75
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).
💻
Java Solution Hidden
Enable “Show Full Solution” to view the code
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