Diameter of Binary Tree - Problem
The diameter of a binary tree is one of the most elegant tree problems that challenges your understanding of tree traversal and path calculations.
Given the root of a binary tree, you need to find the length of the longest path between any two nodes in the tree. This path represents the tree's "diameter" - imagine stretching the tree as wide as possible.
Key Points:
- The path may or may not pass through the root
- The path length is measured by the number of edges (not nodes)
- You need to consider all possible paths, not just root-to-leaf paths
For example, in a tree where the longest path goes from one leaf, up through several ancestors, and down to another leaf on the opposite side, that entire journey's edge count is your answer.
Input & Output
example_1.py — Basic Binary Tree
$
Input:
[1,2,3,4,5]
›
Output:
3
💡 Note:
The longest path is from node 4 to node 5, passing through nodes 2 and then to node 3. Path: 4->2->5 would be length 2, but 4->2->1->3 is length 3.
example_2.py — Single Node
$
Input:
[1]
›
Output:
0
💡 Note:
A single node has no edges, so the diameter is 0.
example_3.py — Skewed Tree
$
Input:
[1,2,null,3,null,4,null]
›
Output:
3
💡 Note:
The longest path goes from node 4 to node 1, passing through nodes 3 and 2. This gives us 3 edges total.
Constraints
- The number of nodes in the tree is in the range [1, 104]
- -100 ≤ Node.val ≤ 100
- Tree nodes contain integer values only
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code