LeetCode 链接:(https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/)
题目:层序遍历的方式遍历多叉树
递归的方式就不用说了,直接写迭代吧。
code如下:
public List<List<Integer>> levelOrder(Node root) {
if(root == null){
return new ArrayList<>();
}
List<List<Integer>> result = new ArrayList<>();
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
//result.add(new ArrayList<>(root.val));
while(!queue.isEmpty()){
// 这里要对当前队列的内容进行遍历
// 因为当前队列中保存的是多叉树中每一层的内容,
// 所以每次下面的for循环是遍历每一层,
// 最下面的for循环是每一层中的每个元素有多少个child,
// 将child塞入队列以便于下一次遍历,因为每一层的个数在
// int size = queue.size()中已经记录,所以不用担心会遍历多出来的node。
int size = queue.size();
List<Integer> temp = new ArrayList<>();
for(int i = 0;i < size;i++){
Node node = queue.poll();
temp.add(node.val);
List<Node>child = node.children;
if(child == null || child.isEmpty()) continue;
for(int j = 0;j < child.size();j++){
queue.offer(child.get(j));
}
}
result.add(temp);
}
return result;
}
}
网友评论