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

思路

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

相关推荐
海域云SeaArea_3 小时前
Windows Server 2008 R2 从零安装 IIS7.5(二):php.ini 配置
开发语言·windows·php
旖旎夜光5 小时前
LeetCode 315: 算右侧小于当前元素的个数(归并排序) —— 题解
c++·学习·算法·leetcode·排序算法
文丑颜不良啊5 小时前
LeetCode1401~1420题目解析
java·leetcode
Nuanyt5 小时前
LeetCode Hot 100 链表专题2 3 题 (Java)
java·笔记·算法·leetcode·链表
文丑颜不良啊5 小时前
LeetCode1341~1360题目解析
java·leetcode
海绵宝宝转agent6 小时前
LeetCodehot100题解
java·笔记·学习·算法·leetcode·深度优先
IsITGirl6 小时前
VMware Fusion(Mac)Windows ARM 虚拟机 NAT (vmnet8) 报错解决记录
windows·macos·.net·桥接模式
Rudon滨海渔村7 小时前
台式机Win10实现“音量+”和“音量-”,键盘映射方案
windows·计算机外设·powertoys
2501_915921437 小时前
KXBuild CI 实操,Windows/Linux 服务器接入 Jenkins 打包 iOS IPA
服务器·windows·vscode·ios·ci/cd·个人开发·敏捷流程
Pniubi7 小时前
力扣543二叉树的直径(深度优先搜索法(递归))
算法·leetcode·职场和发展