题解
就是一层翻转一层不翻转,大水题,与前面两篇博文类似
代码
package main func main() { } type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func zigzagLevelOrder(root *TreeNode) [][]int { return levelOrder(root) } func reverse(cnt []int) []int { for i, j := 0, len(cnt)-1; i < j; i, j = i+1, j-1 { cnt[i], cnt[j] = cnt[j], cnt[i] } return cnt } func levelOrder(root *TreeNode) [][]int { if root == nil { return nil } result := make([][]int, 0) queue := make([]*TreeNode, 0) queue = append(queue, root) f:=true for len(queue) > 0 { cnt := make([]int, 0) queueSize := len(queue) for i := 0; i < queueSize; i++ { //出队 v := queue[0] queue = queue[1:] //入队 if v.Left != nil { queue = append(queue, v.Left) } if v.Right != nil { queue = append(queue, v.Right) } cnt = append(cnt, v.Val) } if f{ result = append(result, cnt) f=false } else{ result = append(result, reverse(cnt)) f=true } } return result }