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
123456Longest Path: 4โ†’2โ†’1โ†’3โ†’6 (Length: 4)Path Analysis Through Node 1:Left subtree max depth: 2 (path to nodes 4 or 5)Right subtree max depth: 2 (path to node 6)Diameter through node 1: 2 + 2 = 4 edges
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.
Asked in
Google 28 Amazon 22 Microsoft 18 Meta 15 Apple 12
87.2K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen