515.find-largest-value-in-each-tree-row.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 largestValues(root *TreeNode) (res []int) {
  10. preorder(root, 0, &res) // DFS
  11. return
  12. }
  13. func preorder(root *TreeNode, depth int, res *[]int) {
  14. if root == nil {
  15. return
  16. }
  17. if depth == len(*res) {
  18. *res = append(*res, root.Val)
  19. } else if (*res)[depth] < root.Val {
  20. (*res)[depth] = root.Val
  21. }
  22. preorder(root.Left, depth+1, res)
  23. preorder(root.Right, depth+1, res)
  24. }
  25. func largestValuesBFS(root *TreeNode) (res []int) {
  26. if root == nil {
  27. return
  28. }
  29. queue := make([]*TreeNode, 0)
  30. queue = append(queue, root)
  31. size := 1
  32. for size != 0 {
  33. max, l := queue[0].Val, size
  34. for i := 0; i < l; i++ {
  35. node := queue[0]
  36. queue = queue[1:]
  37. size--
  38. if max < node.Val {
  39. max = node.Val
  40. }
  41. if node.Left != nil {
  42. queue = append(queue, node.Left)
  43. size++
  44. }
  45. if node.Right != nil {
  46. queue = append(queue, node.Right)
  47. size++
  48. }
  49. }
  50. res = append(res, max)
  51. }
  52. return
  53. }