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

相关推荐
1024小神5 小时前
tauri项目在windows上的c盘没有权限写入文件
c语言·开发语言·windows
程序视点13 小时前
Window 10文件拷贝总是卡很久?快来试试这款小工具,榨干硬盘速度!
windows
wuk99814 小时前
基于MATLAB编制的锂离子电池伪二维模型
linux·windows·github
lzb_kkk15 小时前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
Paper_Love1 天前
x86-64_windows交叉编译arm_linux程序
arm开发·windows
前端若水1 天前
通过 Windows 共享文件夹 + 手机访问(SMB协议)如何实现
windows·智能手机
超龄超能程序猿1 天前
dnSpy 使用教程
windows·microsoft
路来了2 天前
Python小工具之PDF合并
开发语言·windows·python
csdn_aspnet2 天前
在 Windows 上安装和运行 Apache Kafka
windows·kafka
江山如画,佳人北望2 天前
C#程序入门
开发语言·windows·c#