Description:
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.
题意:给定一颗N-叉树,返回其层次遍历的节点值;
解法:不管是二叉树还是N叉树,对于层次遍历我们都可以利用队列来实现;算法流程如下:
- 首先,将根节点入队
- 当队列不为空时,计算当前队列长度,即当前层节点数
- 取出当前层所有节点,并且将其孩子节点入队
- 继续第2步直到队列为空
Java
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val,List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Deque<Node> nodes = new ArrayDeque<>();
nodes.addLast(root);
while (!nodes.isEmpty()) {
int len = nodes.size();
List<Integer> temp = new ArrayList<>();
while (len-- > 0) {
Node node = nodes.removeFirst();
temp.add(node.val);
for (int i = 0; i < node.children.size(); i++) {
nodes.addLast(node.children.get(i));
}
}
result.add(temp);
}
return result;
}
}