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
Diameter of Binary Tree INPUT Binary Tree Structure: 1 2 3 4 5 Input Array: 1 2 3 4 5 [1,2,3,4,5] ALGORITHM - DFS 1 DFS Traversal Visit each node recursively 2 Calculate Heights Get left and right subtree heights 3 Update Diameter diameter = max(left + right) 4 Return Height Return 1 + max(left, right) Longest Path Through Node 2: 2 4 5 Path: 4 --> 2 --> 5 (2 edges) FINAL RESULT Longest Path Found: 1 2 3 4 5 Diameter Path (orange) 4 --> 2 --> 1 --> 3 Output: 3 OK - 3 edges Key Insight: The diameter at any node = left subtree height + right subtree height. By tracking the maximum diameter seen during DFS traversal, we find the global maximum. Time Complexity: O(n) | Space Complexity: O(h) where h is tree height. TutorialsPoint - Diameter of Binary Tree | DFS Approach
Asked in
Google 28 Amazon 22 Microsoft 18 Meta 15 Apple 12
87.3K 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