Question
429. N-ary Tree Level Order Traversal
Solution
题目大意:
N叉树,返回每层的值,从上到下,从左到右
思路:
利用队列遍历这个N叉树
Java实现:
public List<List<Integer>> levelOrder(Node root) {
// N叉树的遍历
List<List<Integer>> retList = new ArrayList<>();
if (root == null) return retList;
Queue<Node> nodeQueue = new LinkedList<>();
nodeQueue.offer(root);
while(!nodeQueue.isEmpty()) {
List<Integer> layerNodeList = new ArrayList<>();
int curLayerSize = nodeQueue.size();
for (int i = 0; i < curLayerSize; i++) {
Node cur = nodeQueue.poll();
layerNodeList.add(cur.val);
if (cur.children != null) {
for (Node tmp : cur.children) {
nodeQueue.offer(tmp);
}
}
}
retList.add(layerNodeList);
}
return retList;
}