513.find-bottom-left-tree-value.go 637 B

12345678910111213141516171819202122232425262728293031323334
  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. func findBottomLeftValue(root *TreeNode) int {
  10. if root == nil {
  11. return -1
  12. }
  13. queue := make([]*TreeNode, 0)
  14. queue = append(queue, root)
  15. for len(queue) != 0 {
  16. bl := queue[0].Val
  17. nextLV := make([]*TreeNode, 0)
  18. for len(queue) != 0 {
  19. head := queue[0]
  20. queue = queue[1:]
  21. if head.Left != nil {
  22. nextLV = append(nextLV, head.Left)
  23. }
  24. if head.Right != nil {
  25. nextLV = append(nextLV, head.Right)
  26. }
  27. }
  28. if len(nextLV) == 0 {
  29. return bl
  30. }
  31. queue = nextLV
  32. }
  33. return -1
  34. }