Golang | Leetcode Golang题解之第103题二叉树的锯齿形层序遍历

题目:

题解:

Go 复制代码
func zigzagLevelOrder(root *TreeNode) (ans [][]int) {
    if root == nil {
        return
    }
    queue := []*TreeNode{root}
    for level := 0; len(queue) > 0; level++ {
        vals := []int{}
        q := queue
        queue = nil
        for _, node := range q {
            vals = append(vals, node.Val)
            if node.Left != nil {
                queue = append(queue, node.Left)
            }
            if node.Right != nil {
                queue = append(queue, node.Right)
            }
        }
        // 本质上和层序遍历一样,我们只需要把奇数层的元素翻转即可
        if level%2 == 1 {
            for i, n := 0, len(vals); i < n/2; i++ {
                vals[i], vals[n-1-i] = vals[n-1-i], vals[i]
            }
        }
        ans = append(ans, vals)
    }
    return
}
相关推荐
xcLeigh2 小时前
Go入门:变量声明的五种方式详解
java·开发语言·golang
皓月斯语6 小时前
B2118 验证子串
c++·题解
Hi李耶6 小时前
【LeetCode】4-寻找两个正序数组的中位数
算法·leetcode·职场和发展
Hi李耶10 小时前
【LeetCode】6-Z字形变换
算法·leetcode·职场和发展
AKA__Zas10 小时前
芝士算法(前缀和2.0)
java·数据结构·算法·leetcode·哈希算法·学习方法
皓月斯语11 小时前
B3867 [GESP202309 三级] 小杨的储蓄 题解
c++·算法·题解
techdashen11 小时前
Go设计取舍之三: 0.3ns每次的错误Benchmark
开发语言·后端·golang
XWalnut11 小时前
LeetCode刷题 day33
java·数据结构·算法·leetcode
闪电悠米12 小时前
力扣hot100-142.环形链表II-哈希集合与快慢指针详解
leetcode·链表·哈希算法
Tisfy12 小时前
LeetCode 0486.预测赢家:深度优先搜索(DFS)
算法·leetcode·深度优先·dfs·博弈