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
Diameter of N-Ary Tree INPUT N-ary Tree Structure 1 3 2 4 5 6 root = [1,null,3,2,4, null,5,6] Edges represent connections between parent and children ALGORITHM STEPS 1 DFS Traversal Start from root, visit all children recursively 2 Calculate Heights For each node, compute height of all subtrees 3 Track Max Diameter At each node: sum of 2 largest child heights 4 Return Max Height Return 1 + max child height to parent Height Calculation Node 5: h=0, Node 6: h=0 Node 3: h=1 (max 0,0)+1 Node 2: h=0, Node 4: h=0 Node 1: h=2 (max 1,0,0)+1 FINAL RESULT Longest Path Highlighted 1 3 2 4 5 6 Path: 5 --> 3 --> 1 --> 4 Edges: 3 Output: 3 Key Insight: The diameter through any node equals the sum of the two largest heights among its children. We track the global maximum diameter while returning the height (1 + max child height) for parent calculation. Time: O(N) - visit each node once. Space: O(H) - recursion stack where H is tree height. TutorialsPoint - Diameter of N-Ary Tree | DFS with Height Calculation Approach
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