LeetCode-热题100-笔记-day27

2. 二叉树的层序遍历https://leetcode.cn/problems/binary-tree-level-order-traversal/

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

示例 1:

复制代码
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]

算法思路

二叉树层次遍历,先建立队列,将根节点放入队列后,出队将出队的节点左右子树放入队列重复上述操作;

java 复制代码
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans=new ArrayList<List<Integer>>();
        if(root==null){
            return ans;
        }
        Queue<TreeNode> queue=new ArrayDeque<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size=queue.size();
            List<Integer> level=new ArrayList<>();
            for(int i=1;i<=size;i++){
                TreeNode cur=queue.poll();
                level.add(cur.val);
                if(cur.left!=null){
                    queue.offer(cur.left);
                }
                if(cur.right!=null){
                    queue.offer(cur.right);
                }
            }
            ans.add(level);
        }
        return ans;
    }
}
相关推荐
笑衬人心。44 分钟前
Ubuntu 22.04 修改默认 Python 版本为 Python3 笔记
笔记·python·ubuntu
金色光环1 小时前
【Modbus学习笔记】stm32实现Modbus
笔记·stm32·学习
向阳@向远方2 小时前
第二章 简单程序设计
开发语言·c++·算法
zyxzyx6662 小时前
Flyway 介绍以及与 Spring Boot 集成指南
spring boot·笔记
github_czy2 小时前
RRF (Reciprocal Rank Fusion) 排序算法详解
算法·排序算法
许愿与你永世安宁3 小时前
力扣343 整数拆分
数据结构·算法·leetcode
爱coding的橙子3 小时前
每日算法刷题Day42 7.5:leetcode前缀和3道题,用时2h
算法·leetcode·职场和发展
西岭千秋雪_4 小时前
Redis性能优化
数据库·redis·笔记·学习·缓存·性能优化
满分观察网友z4 小时前
从一次手滑,我洞悉了用户输入的所有可能性(3330. 找到初始输入字符串 I)
算法
YuTaoShao4 小时前
【LeetCode 热题 100】73. 矩阵置零——(解法二)空间复杂度 O(1)
java·算法·leetcode·矩阵