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