【hot100-java】【二叉树的层序遍历】

二叉树

BFS

队列实现

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) {
        Queue<TreeNode> queue=new LinkedList<>();
        List<List<Integer>>ret=new ArrayList<>();
        if(root!=null) queue.add(root);
        while(!queue.isEmpty()){
            List<Integer>tmp=new ArrayList<>();
            for(int i=queue.size();i>0;i--){
                TreeNode node=queue.poll();
                tmp.add(node.val);
                if(node.left!=null) queue.add(node.left);
                if(node.right!=null) queue.add(node.right);
            }
            ret.add(tmp);
        }
        return ret;
        
        
    }
}
相关推荐
汝生淮南吾在北1 小时前
SpringBoot+Vue饭店点餐管理系统
java·vue.js·spring boot·毕业设计·毕设
fish_xk2 小时前
c++中的引用和数组
开发语言·c++
酒尘&4 小时前
JS数组不止Array!索引集合类全面解析
开发语言·前端·javascript·学习·js
tzhou644525 小时前
MySQL备份与恢复
数据库·mysql·adb
冬夜戏雪5 小时前
【java学习日记】【2025.12.7】【7/60】
java·开发语言·学习
xwill*5 小时前
分词器(Tokenizer)-sentencepiece(把训练语料中的字符自动组合成一个最优的子词(subword)集合。)
开发语言·pytorch·python
CC.GG5 小时前
【C++】二叉搜索树
java·c++·redis
一过菜只因5 小时前
MySql Jdbc
android·数据库·mysql
咖啡の猫5 小时前
Python列表的查询操作
开发语言·python
思成不止于此5 小时前
MySQL 查询实战(三):排序与综合练习
数据库·笔记·学习·mysql