领扣(LeetCode)N叉树的层序遍历 个人题解

给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。

例如,给定一个 3叉树 :

返回其层序遍历:

[
     [1],
     [3,2,4],
     [5,6]
]

说明:

  1. 树的深度不会超过 1000
  2. 树的节点总数不会超过 5000

二叉树的层序遍历的升级版,做法思路类似,使用队列存放当前层的所有节点,遍历所有层。可以参考我往期的二叉树层次遍历的做法 https://www.cnblogs.com/axiangcoding/p/10013327.html

本题代码如下:

 1 class Solution {
 2     public List<List<Integer>> levelOrder(Node root) {
 3         if(root==null)
 4             return null;
 5         List<List<Integer>> ans=new ArrayList<>();
 6         Queue<Node> queue=new LinkedList<>();
 7         queue.add(root);
 8         while(!queue.isEmpty())
 9         {
10             List<Integer> secans=new ArrayList<>();
11             Queue<Node> qtmp=new LinkedList<>();
12             while(!queue.isEmpty())
13             {
14                 Node ntmp=queue.poll();
15                 secans.add(ntmp.val);
16                 List<Node> chil=ntmp.children;
17                 for(int i=0;i<chil.size();i++)
18                 {
19                     if(chil.get(i)!=null)
20                         qtmp.add(chil.get(i));
21                 }
22             }
23             queue=qtmp;
24             ans.add(secans);
25         }
26         return ans;
27     }
28 
29 }

猜你喜欢

转载自www.cnblogs.com/axiangcoding/p/10092160.html