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

相关推荐
攻城狮在此3 小时前
SecureCRT与MobaXterm详细对比:哪个更强、谁更适合你?
windows
love530love4 小时前
冷门干货!llama.cpp 自带原生网页聊天 UI,无需第三方依赖一键开启
人工智能·windows·ui·llama·flash-attention·switch-cuda
gordon~95 小时前
Windows 11 wsl 中安装的Ubuntu-24.04 中装docker
windows·ubuntu·docker
历程里程碑6 小时前
Protobuf 环境搭建:Windows 与 Linux 系统安装教程
linux·运维·数据结构·windows·线性代数·算法·矩阵
tobebetter95277 小时前
WSL2 + Windows + remote Chrome CDP openclaw 浏览器自动化
chrome·windows·自动化
桌面运维家8 小时前
解决Windows 10打印机脱机:端口、驱动、网络故障排除
windows·stm32·单片机
liwulin05068 小时前
【ROS2】【ESP32S3纯透传方案】ESP32S3+WINDOWS+VMware+ROS2+YDLIDA X导航完整落地方案
windows·stm32·单片机
AxureMost9 小时前
MTools 0.0.12-beta 全能工具箱
windows·开源软件
beyond阿亮10 小时前
OpenClaw在Windows上接入飞书完整指南
人工智能·windows·ai·openclaw
大强同学12 小时前
MFCMouseEffect 鼠标可视化特效设置与操作教程
windows·鼠标手势