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

思路

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

相关推荐
smj2302_796826523 分钟前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
John_ToDebug15 分钟前
隐于无形,触手可及:Chrome 互动滚动条的六个设计密码
chrome·windows·ui
思茂信息1 小时前
CST软件如何进行参数化扫描?
运维·开发语言·javascript·windows·ecmascript·软件工程·软件需求
开发者联盟league3 小时前
在windows上安装和运行rocketmq
windows·rocketmq
_深海凉_4 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
踩坑记录5 小时前
leetcode hot100 寻找两个正序数组的中位数 hard 二分查找 双指针
leetcode
非凡ghost5 小时前
可拓浏览器:给手机浏览器装上“外挂“!2W+拓展+AI搜索,玩出无限可能!
windows·智能手机·音视频·firefox
小神.Chen5 小时前
如何删除远程桌面的连接记录,一键清理mstsc远程桌面连接的记录
windows
John_ToDebug5 小时前
WebHostView 与 TabStrip 交互机制深度解析
c++·chrome·windows
L1624766 小时前
Win11 共享→Windows Server 访问故障总结(极简可复用)
开发语言·windows·php