Diameter of N-Ary Tree - Problem

🌳 Find the Diameter of an N-Ary Tree

Given the root of an N-ary tree, you need to find the diameter - the length of the longest path between any two nodes in the tree. This path may or may not pass through the root.

What makes this challenging? Unlike binary trees where each node has at most 2 children, N-ary trees can have any number of children. The longest path could wind through multiple levels and branches.

Key Points:

  • The diameter is measured in number of edges, not nodes
  • The longest path might be between two leaf nodes deep in different subtrees
  • We need to consider all possible paths, not just those through the root

Input: Root of an N-ary tree (level-order serialization with null separators)
Output: Integer representing the diameter (longest path length)

Input & Output

example_1.py β€” Simple N-ary Tree
$ Input: root = [1,null,2,3,null,5,6]\nTree structure:\n 1\n / \\\n 2 3\n / \\\n5 6
β€Ί Output: 3
πŸ’‘ Note: The longest path is between nodes 5β†’2β†’6 or 5β†’2β†’1β†’3, both with length 3 edges.
example_2.py β€” Larger Tree
$ Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\nTree with multiple levels and branches
β€Ί Output: 7
πŸ’‘ Note: The diameter passes through several nodes connecting the deepest leaves on opposite sides of the tree.
example_3.py β€” Single Node
$ Input: root = [1]\nTree with only one node
β€Ί Output: 0
πŸ’‘ Note: A single node has no edges, so the diameter is 0.

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • -100 <= Node.val <= 100
  • The depth of the n-ary tree is less than or equal to 1000
  • Each node can have any number of children (including 0)

Visualization

Tap to expand
N-Ary Tree Diameter Calculation12345678Longest Path: 5β†’2β†’6β†’3β†’7 (Length = 4)Algorithm: For each node, find two tallest child subtreesDiameter through node = height₁ + heightβ‚‚ + 2
Understanding the Visualization
1
Understand the Problem
The diameter is the longest path between any two nodes, measured in edges
2
Key Insight
The longest path through any node equals the sum of its two longest descending paths
3
DFS Approach
Use post-order DFS to calculate child heights before processing parent
4
Track Maximum
Keep track of maximum diameter found across all nodes during traversal
Key Takeaway
🎯 Key Insight: The diameter of an N-ary tree can be found in O(n) time using a single DFS traversal, where we calculate the two longest paths from each node to its descendants.
Asked in
Google 45 Amazon 35 Meta 28 Microsoft 22
42.0K Views
Medium Frequency
~25 min Avg. Time
1.5K 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