Leetcode—102. 二叉树的层序遍历【中等】

2025每日刷题(246)

Leetcode---102. 二叉树的层序遍历

实现代码

go 复制代码
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func levelOrder(root *TreeNode) [][]int {
    ans := make([][]int, 0)
    q := make([]*TreeNode, 0)
    if root == nil {
        return ans
    }
    q = append(q, root)
    for len(q) > 0 {
        cur := make([]int, 0)
        n := len(q)
        for range n {
            t := q[0]
            q = q[1:]
            cur = append(cur, t.Val)
            if t.Left != nil {
                q = append(q, t.Left)
            }
            if t.Right != nil {
                q = append(q, t.Right)
            }
        }
        ans = append(ans, cur)
    }
    return ans
}

运行结果

之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
政企项目老覃2 小时前
大模型幻觉治理与自动评测:金融风控场景的落地实践
人工智能·算法·机器学习
淡海水2 小时前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
hansang_IR2 小时前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
洛阳纸贵2 小时前
MATLAB-matlab基础知识
学习·算法·matlab
落羽的落羽3 小时前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
Nil2083 小时前
leetcode 17电话号码的字母组合
算法·leetcode·职场和发展
IT_陈寒4 小时前
Python的多线程就是个假把式,我算是体验到了
前端·人工智能·后端
码事漫谈4 小时前
如果 AI 要圈养人类,它可能不需要笼子
后端