题解
就是上一篇博文加一个翻转
代码
package main func main() { } type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func levelOrderBottom(root *TreeNode) [][]int { result := levelOrder(root) return reverse(result) } 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) 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) } result = append(result, cnt) } return result }