Medium · Trees
N-ary tree diameter
Given the root of an N-ary tree, return its diameter: the number of edges on the longest path between any two nodes (0 for an empty or single-node tree).
Examples
Example 1
tree=[1,2,3,4,null,5,null,6] (binary-indexed slots: child indices 2i+1 and 2i+2)Output: diameter = 5
Example 2
{
"nodes": [
{"val": 1, "children": [1]},
{"val": 2, "children": [2]},
{"val": 3, "children": [3]},
{"val": 4, "children": []}
]
}Output: diameter = 3
Rebuild it in the studio
Open every published interview problem, solution, scene, and memory room free, with no account.