【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;
        
        
    }
}
相关推荐
望获linux26 分钟前
【Linux基础知识系列:第一百五十九篇】磁盘健康监测:smartctl
linux·前端·数据库·chrome·python·操作系统·软件
西部风情32 分钟前
聊聊并发、在线、TPS
android·java·数据库
爬虫程序猿2 小时前
用 Python 给京东商品详情做“全身 CT”——可量产、可扩展的爬虫实战
开发语言·爬虫·python
顾漂亮2 小时前
Token快过期的三种续期方案
java·spring·状态模式
侯小啾3 小时前
【03】C语言 强制类型转换 与 进制转换
c语言·数据结构·算法
Xの哲學3 小时前
Linux NAPI 架构详解
linux·网络·算法·架构·边缘计算
徐同保3 小时前
tailwindcss暗色主题切换
开发语言·前端·javascript
蓝纹绿茶3 小时前
bash:**:pip:***python: 错误的解释器: 没有那个文件或目录
开发语言·python·pip
云知谷4 小时前
【经典书籍】C++ Primer 第15章类虚函数与多态 “友元、异常和其他高级特性” 精华讲解
c语言·开发语言·c++·软件工程·团队开发
清风6666664 小时前
基于单片机的水塔液位检测与智能调节报警系统设计
数据库·单片机·嵌入式硬件·毕业设计·课程设计·期末大作业