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
}

运行结果

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

相关推荐
NAGNIP1 天前
轻松搞懂全连接神经网络结构!
人工智能·算法·面试
勇哥java实战分享1 天前
程序员的明天:AI 时代下的行业观察与个人思考
后端
NAGNIP1 天前
一文搞懂激活函数!
算法·面试
董董灿是个攻城狮1 天前
AI 视觉连载7:传统 CV 之高斯滤波实战
算法
掘金码甲哥1 天前
超性感的轻量级openclaw平替,我来给你打call
后端
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
啊哈灵机一动1 天前
使用golang搭建一个nes 模拟器
后端
间彧1 天前
SpringBoot + ShardingSphere 读写分离实战指南
后端
砍材农夫1 天前
订单超时
后端