Diameter of N-Ary Tree - Problem

Given a root of an N-ary tree, you need to compute the length of the diameter of the tree.

The diameter of an N-ary tree is the length of the longest path between any two nodes in the tree. This path may or may not pass through the root.

Note: The length of a path between two nodes is represented by the number of edges between them.

Input & Output

Example 1 — Standard N-ary Tree
$ Input: root = [1,null,3,2,4,null,5,6]
Output: 3
💡 Note: The longest path is from node 5 → 3 → 1 → 2, which has 3 edges. The diameter passes through the root node 1.
Example 2 — Single Node
$ Input: root = [1]
Output: 0
💡 Note: A single node has no edges, so the diameter is 0.
Example 3 — Linear Tree
$ Input: root = [1,null,2,null,3,null,4]
Output: 3
💡 Note: The tree forms a linear chain: 1 → 2 → 3 → 4. The diameter is the path from 1 to 4, which has 3 edges.

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • 0 ≤ Node.val ≤ 100

Visualization

Tap to expand
N-Ary Tree Diameter: Find Longest Path132456Tree StructurePossible paths:5 → 3 → 1 → 2 (3 edges)6 → 3 → 1 → 4 (3 edges)5 → 3 → 6 (2 edges)2 → 1 → 4 (2 edges)Output: Diameter = 3Longest path has 3 edges between any two nodes
Understanding the Visualization
1
Input Tree
N-ary tree with nodes and edges
2
Find Paths
Identify all possible paths between node pairs
3
Maximum Length
Return length of longest path (number of edges)
Key Takeaway
🎯 Key Insight: The diameter is the sum of the two deepest subtree heights at any node
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
89.4K Views
Medium Frequency
~25 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