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;
    }
}
相关推荐
一只大鸽子8 小时前
游戏开发笔记12-像素画基础-细节
笔记
lisw0512 小时前
稀疏算法概述!
算法·机器人·无人机
YLCHUP14 小时前
【括号匹配+dp优化】题解:双端括号(brackets)_动态规划_状态优化_数学建模_贪心_性质挖掘_STLmap_C++算法竞赛
数据结构·c++·笔记·算法·数学建模·贪心算法·动态规划
郝学胜-神的一滴15 小时前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl
云半S一17 小时前
Agent学习总结补充:3
经验分享·笔记·agent·学习分享
geovindu19 小时前
python:Logistic Regression
开发语言·后端·python·算法
摇滚侠20 小时前
《On Java 中文版 基础卷》阅读笔记 内部类 21
java·开发语言·笔记
geovindu20 小时前
python: Random Forest
开发语言·后端·python·算法·随机森林
凌冰_21 小时前
数据结构 - 线性结构(三)
java·数据结构·算法·软件工程