[leetcode] problem 429 – n-ary tree level order traversal

Given an n-ary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example, given a 3-ary tree:

E69bqA.png

We should return its level order traversal:

1
2
3
4
5
[
[1],
[3,2,4],
[5,6]
]

Note

  1. The depth of the tree is at most 1000.
  2. The total number of nodes is at most 5000.

Code

1
2
3
4
5
6
7
8
public class  {
public int val;
public List<Node> children;
public (int _val, List<Node> _children) {
val = _val;
children = _children;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> result = new ArrayList<>();

if (root == null)
return result;

Queue<Node> queue = new LinkedList<>();
queue.offer(root);

while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> nodes = new ArrayList<>();

for (int i = 0; i < size; i++) {
Node node = queue.poll();
nodes.add(node.val);
List<Node> children = node.children;

if (children != null) {
for (Node child : children)
queue.offer(child);
}
}

result.add(nodes);
}

return result;
}