(leetcode)力扣100 41二叉树的层序遍历(bfs)

题目

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

数据范围

树中节点数目在范围 [0, 2000] 内

-1000 <= Node.val <= 1000

测试用例

示例1

java 复制代码
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]

示例2

java 复制代码
输入:root = [1]
输出:[[1]]

示例3

java 复制代码
输入:root = []
输出:[]

题解

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    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 num=queue.size();
            List<Integer> list=new ArrayList<>();
            while(num--!=0){
                TreeNode temp=queue.poll();
                list.add(temp.val);
                if(temp.left!=null)
                    queue.add(temp.left);

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

            res.add(list);
        }
        return res;
    }
}

思路

太简单了代码备注不想给,思路也不想写 = =

相关推荐
阿白的白日梦7 小时前
winget基础管理---更新/修改源为国内源
windows
埃博拉酱4 天前
VS Code Remote SSH 连接 Windows 服务器卡在"下载 VS Code 服务器":prcdn DNS 解析失败的诊断与 BITS 断点续传
windows·ssh·visual studio code
唐宋元明清21885 天前
.NET 本地Db数据库-技术方案选型
windows·c#
加号35 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
琢磨先生David5 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
tryCbest5 天前
Windows环境下配置pip镜像源
windows·pip
呉師傅5 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑
百事牛科技5 天前
保护文档安全:PDF限制功能详解与实操
windows·pdf
一个人旅程~5 天前
如何用命令行把win10/win11设置为长期暂停更新?
linux·windows·经验分享·电脑
超级大福宝5 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode