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:
We should return its level order traversal:
```
[
[1],
[3,2,4],
[5,6]]
````
Note:
The depth of the tree is at most 1000.
The total number of nodes is at most 5000.
解题思路
这道题的思路跟二叉树的层次遍历一样,只不过多叉树需要多加一个遍历。我们需要一个队列,但是里面的节点是一个List
集合。迭代的时候每次弹出的节点集合,我们需要遍历集合的所有子节点然后放入队列。此时结果集也增加一层。迭代整个过程
最终运行结果战胜 64.89 %
的 java 提交记录,属于一般般的解法,还有很大的优化空间。提示下,更好的解法是用递归。
代码如下:
/*
// Definition for a Node.
class Node {
public int val;
public List children;
public Node() {}
public Node(int _val,List _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public List> levelOrder(Node root) {
List> resultList=new ArrayList<>();
if(root==null) return resultList;
Queue> queue=new LinkedList<>();
List list=new ArrayList<>();
list.add(root);
queue.add(list);
while(!queue.isEmpty()){
List result=new ArrayList<>();
List childLayer=new ArrayList<>();
List cur=queue.poll();
for(Node i:cur){
if(i.children!=null&&i.children.size()>0){
childLayer.addAll(i.children);
}
result.add(i.val);
}
resultList.add(result);
if(childLayer.size()>0){
queue.add(childLayer);
}
}
return resultList;
}
}