【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;
        
        
    }
}
相关推荐
熊猫钓鱼>_>12 小时前
Java面向对象核心面试技术考点深度解析
java·开发语言·面试·面向对象··class·oop
她说彩礼65万12 小时前
C# 代理模式
开发语言·c#·代理模式
寂静山林12 小时前
UVa 1366 Martian Mining
算法
程序员大雄学编程12 小时前
用Python来学微积分34-定积分的基本性质及其应用
开发语言·python·数学·微积分
liu****12 小时前
12.线程(二)
linux·开发语言·c++·1024程序员节
黄暄12 小时前
微服务面试题(14题)
java·spring cloud·微服务·架构·java-rabbitmq·java-zookeeper
DKPT12 小时前
如何设置JVM参数避开直接内存溢出的坑?
java·开发语言·jvm·笔记·学习
萤丰信息13 小时前
智慧园区系统:开启园区管理与运营的新时代
java·大数据·人工智能·安全·智慧城市·智慧园区
一 乐13 小时前
智慧党建|党务学习|基于SprinBoot+vue的智慧党建学习平台(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·学习
林一百二十八13 小时前
Python实现手写数字识别
开发语言·python