429. N-ary Tree Level Order Traversal

429. N-ary Tree Level Order Traversal

Question

Given an n-ary tree, return the level order traversal of its nodes’ values.

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

Solution

BFS搜索,层序遍历。
用level记录上一层的个数。
当队列不为空时,每次挤出level个节点,并将其子节点加入队列。
将当前层次的节点值加入列表。
最后更新level的数量。

Code

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
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;

public Node() {}

public Node(int _val) {
val = _val;
}

public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/

class Solution {
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
Queue<Node> q = new LinkedList<>();
q.add(root);
int level = 1;

while(!q.isEmpty()){
List<Integer> arr = new ArrayList<>();
for(int i = 0; i < level; i++){
Node curr = q.poll();
for(Node child : curr.children){
q.offer(child);
}
arr.add(curr.val);
}
res.add(arr);
level = q.size();
}
return res;
}
}
Author

Xander

Posted on

2022-09-04

Updated on

2022-09-04

Licensed under

Comments