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:
思路: Simple BFS
Time Complexity: O(N) Space Complexity: O(N)
Solution Code:
class Solution {
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()) {
List<Integer> curLevelResult = new ArrayList<>();
int size = queue.size();
for (int i = 0; i < size; i++) {
Node curNode = queue.poll();
curLevelResult.add(curNode.val);
for (Node child : curNode.children) {
queue.offer(child);
}
}
result.add(curLevelResult);
}
return result;
}
}