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
}
运行结果

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