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;
    }
}
相关推荐
.YM.Z11 分钟前
【数据结构】:排序(一)
数据结构·算法·排序算法
Chat_zhanggong34514 分钟前
K4A8G165WC-BITD产品推荐
人工智能·嵌入式硬件·算法
百***480729 分钟前
【Golang】slice切片
开发语言·算法·golang
墨染点香42 分钟前
LeetCode 刷题【172. 阶乘后的零】
算法·leetcode·职场和发展
做怪小疯子44 分钟前
LeetCode 热题 100——链表——反转链表
算法·leetcode·链表
智者知已应修善业1 小时前
【51单片机普通延时奇偶灯切换】2023-4-4
c语言·经验分享·笔记·嵌入式硬件·51单片机
wdfk_prog1 小时前
[Linux]学习笔记系列 -- [block]bio
linux·笔记·学习
做怪小疯子3 小时前
LeetCode 热题 100——矩阵——旋转图像
算法·leetcode·矩阵
努力学习的小廉3 小时前
我爱学算法之—— BFS之最短路径问题
算法·宽度优先
高山上有一只小老虎3 小时前
构造A+B
java·算法