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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code