codeTop102:二叉树的层序遍历

前言

在已知BFS的方式后,知道每次从队列中取一个节点,就要将这个节点的所有子节点按照顺序放入队列。

难点在于怎么确定将同一层的节点放在一个数组里面的输出,也就是输出一个二维数组?

解决方法:

每次while循环将队列上轮放入的节点全部取出(之前的普通BFS是每次whie循环只取一个节点)。

java 复制代码
 public  List<List<Integer>> levelOrder(TreeNode root) {
    List<List<Integer>> res = new ArrayList<>();
    if (root == null){
        return res;
    }
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(root);

    while (!queue.isEmpty()){

        int size = queue.size();
        List<Integer> temp = new ArrayList<>();
        for (int i = 0 ; i < size; i++ ){
            TreeNode target = queue.poll();
            temp.add(target.val);

            if (target.left != null){
                queue.add(target.left);
            }

            if (target.right != null){
                queue.add(target.right);
            }
        }

        res.add(temp);

    }

   return res;
}

相关推荐
hERS EOUS37 分钟前
Redis 下载与安装 教程 windows版
数据库·windows·redis
爱吃香蕉的阿豪1 小时前
Mac 远程操作 Windows 开发:ZeroTier + JetBrains 实战指南
windows·macos·zerotoer
YJlio2 小时前
2026年4月18日60秒读懂世界:从神舟二十号出舱到L2新国标公示,今天最值得关注的6个信号
windows·python·django·计算机外设·电脑·outlook·eixv3
代码小书生10 小时前
Windows X-Lite Win11 26H1 v3 游戏优化系统!集Win11、Win10、Win7三代优点,兼顾游戏办公生产算力,系统精简纯净!
windows·win10·电脑系统·windows10·26h1·windows x-lite·操作系统操作系统
贵沫末12 小时前
python——打包自己的库并安装
开发语言·windows·python
小眼哥13 小时前
SpringBoot整合Vue代码生成exe运行程序以及windows安装包
vue.js·windows·spring boot
xiaoshuaishuai813 小时前
C# GPU算力与管理
开发语言·windows·c#
꯭爿꯭巎꯭16 小时前
千鹿PR助手邀请码
windows
张赐荣18 小时前
跨平台无障碍版随机数生成器
windows