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
Understanding the Visualization
1
Identify All Paths
Every possible path between two nodes could potentially be the diameter
2
Key Insight
The longest path must pass through some node as the highest common ancestor
3
Calculate at Each Node
For each node, the longest path through it equals left subtree height + right subtree height
4
Single Traversal
Use post-order DFS to calculate heights and track maximum diameter simultaneously
Key Takeaway
๐ฏ Key Insight: The diameter of any subtree can be calculated by summing the maximum depths of its left and right children, making post-order traversal perfect for this problem.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code