Medium · Trees
N-ary tree level order
Given an n-ary tree as a list of nodes (node 0 is the root; each node has a value and an ordered list of child indices), return its level-order traversal: a list of levels from top to bottom, each holding that level's values from left to right. An empty tree has no levels (the reference returns null).
Examples
Example 1
{
"nodes": [
{"val": 1, "children": [1, 2, 3]},
{"val": 3, "children": [4, 5]},
{"val": 2, "children": []},
{"val": 4, "children": []},
{"val": 5, "children": []},
{"val": 6, "children": []}
]
}Output: [[1], [3,2,4], [5,6]]
Example 2
{
"nodes": [
{"val": 1, "children": [1, 2]},
{"val": 2, "children": [3, 4, 5]},
{"val": 3, "children": []},
{"val": 4, "children": []},
{"val": 5, "children": []},
{"val": 6, "children": []}
]
}Output: [[1], [2,3], [4,5,6]]
Rebuild it in the studio
Read every interview problem free. Ten rooms need no account. A token opens a problem in full — Pro never counts.