107.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. // TreeNode ...
  6. type TreeNode struct {
  7. Val int
  8. Left *TreeNode
  9. Right *TreeNode
  10. }
  11. func reverseArr(arr *[][]int) {
  12. for i, j := 0, len(*arr)-1; i < j; i, j = i+1, j-1 {
  13. (*arr)[i], (*arr)[j] = (*arr)[j], (*arr)[i]
  14. }
  15. }
  16. func levelOrderBottomIter(curr *TreeNode, depth int, arr *[][]int) {
  17. if curr == nil {
  18. return
  19. }
  20. if curr.Left != nil {
  21. levelOrderBottomIter(curr.Left, depth+1, arr)
  22. }
  23. if curr.Right != nil {
  24. levelOrderBottomIter(curr.Right, depth+1, arr)
  25. }
  26. for len(*arr) < depth+1 {
  27. layer := make([]int, 0)
  28. *arr = append(*arr, layer)
  29. }
  30. (*arr)[depth] = append((*arr)[depth], curr.Val)
  31. }
  32. /**
  33. * Definition for a binary tree node.
  34. * type TreeNode struct {
  35. * Val int
  36. * Left *TreeNode
  37. * Right *TreeNode
  38. * }
  39. */
  40. func levelOrderBottom(root *TreeNode) [][]int {
  41. arr := make([][]int, 0)
  42. levelOrderBottomIter(root, 0, &arr)
  43. reverseArr(&arr)
  44. return arr
  45. }
  46. func main() {
  47. /**
  48. * t1: 5
  49. * / \
  50. * 1 4
  51. * / \
  52. * 2 3
  53. */
  54. t1l := TreeNode{1, nil, nil}
  55. t1rl := TreeNode{2, nil, nil}
  56. t1rr := TreeNode{3, nil, nil}
  57. t1r := TreeNode{4, &t1rl, &t1rr}
  58. t1 := &TreeNode{5, &t1l, &t1r}
  59. t2 := &TreeNode{9, nil, nil}
  60. fmt.Println(levelOrderBottom(t1))
  61. fmt.Println(levelOrderBottom(t2))
  62. }