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;
}

相关推荐
搏博2 小时前
将图形可视化工具的 Python 脚本打包为 Windows 应用程序
开发语言·windows·python·matplotlib·数据可视化
电手3 小时前
Win10停更,Win11不好用?现在Mac电脑比Win11电脑更便宜
windows·macos·电脑·mac
拾回程序猿的圈圈∞3 小时前
PyCharm项目和文件运行时使用conda环境的教程
windows·pycharm·conda
波点兔4 小时前
【亲测有效 | Cursor Pro每月500次快速请求扩5倍】(Windows版)Cursor中集成interactive-feedback-mcp
windows·mcp·cursor pro
饮长安千年月5 小时前
JavaSec-SSTI - 模板引擎注入
java·windows·安全·web安全·网络安全·系统安全·安全架构
字节高级特工8 小时前
【Linux篇】0基础之学习操作系统进程
linux·运维·服务器·数据结构·windows·学习·list
Amo Xiang17 小时前
Python 解释器安装全攻略(适用于 Linux / Windows / macOS)
linux·windows·python·环境安装
小邓儿◑.◑1 天前
C++初阶 | 模板
网络·c++·windows
豆芽脚脚1 天前
spel 多层list嵌套表达式踩坑记
windows·list·spel
饮长安千年月1 天前
玄机-第六章 流量特征分析-蚂蚁爱上树
windows·计算机网络·web安全·网络安全·系统安全·安全架构