⭐北邮复试刷题429. N 叉树的层序遍历(按层入队出队BFS)(力扣每日一题)

429. N 叉树的层序遍历

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

树的序列化输入是用层序遍历,每组子节点都由 null 值分隔(参见示例)。

示例 1:



输入:root = [1,null,3,2,4,null,5,6]
输出:[[1],[3,2,4],[5,6]]

示例 2:



输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
 

提示:
树的高度不会超过 1000
树的节点总数在 [0, 10^4] 之间

在这里插入图片描述

题解:

主要思路就是常规BFS,只不过每次从队列拿元素的时候一次将一层的节点全部拿出,再将这些节点下层的children都同时入队即可。这样会造成最后多一次入队出队,所以最后加上一次判空操作即可;

代码:

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        Queue<Node> queue = new LinkedList<>();
        List<List<Integer>> res = new ArrayList<>();
        if(root == null){
            return res;
        }

        queue.offer(root);
        List<Integer> list = new ArrayList<>();
        list.add(root.val);
        res.add(list);
        while(!queue.isEmpty()){
            // 队列想边拿边加时,则利用长度字段;想只拿不加可以用队列判空,最后队列再加;
            List<List<Node>> tmpList = new ArrayList<>();
            while(!queue.isEmpty()){
                // 出队
                // 将同层的节点一次拿出
                Node tmpQueueOne = queue.poll();
                if(tmpQueueOne.children != null)
                    tmpList.add(tmpQueueOne.children);
            }
            if(tmpList == null || tmpList.size() == 0)
                continue;
            int tmpLen = tmpList.size();
            List<Integer> tmpResOfOne = new ArrayList<>();
            for(int i=0;i<tmpLen;i++){
                if(tmpList.get(i) != null){
                    for(int j=0;j<tmpList.get(i).size();j++){
                        tmpResOfOne.add(tmpList.get(i).get(j).val);
                        // 入队
                        // 将本层下层的孩子全部同时入队
                        queue.offer(tmpList.get(i).get(j));
                    }
                }
            }
            if(tmpResOfOne == null || tmpResOfOne.size() == 0)
                continue;
            res.add(tmpResOfOne);
        }
        return res;
    }
}

在这里插入图片描述

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>