429. N叉树的层序遍历

N叉树的层序遍历

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

例如,给定一个 3叉树 :
在这里插入图片描述

返回其层序遍历:

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

思路+代码+注释:

public List<List<Integer>> levelOrder(Node root) {
        /*
        思路:就是从根节点开始一层一层的遍历,使用BFS借助队列来做
         */
                List<List<Integer>> res=new ArrayList<>();
                if (root==null)
                {
                    return res;
                }
                LinkedList<Node> queue=new LinkedList<>();
                queue.add(root);
                int curSize;
                while ((curSize=queue.size())>0)
                {
                    List<Integer> curNums=new ArrayList<>();
                    for (int i = 0; i < curSize; i++) {
                        Node n=queue.poll();
                        curNums.add(n.val);
                        List<Node> nodes=n.children;
                        for (int j = 0; j < nodes.size(); j++) {
                            queue.add(nodes.get(j));
                        }
                    }
                    res.add(curNums);
                }
                return res;
    }

猜你喜欢

转载自blog.csdn.net/qq_36059306/article/details/88820336