508.most-frequent-subtree-sum.go 612 B

1234567891011121314151617181920212223242526272829303132333435
  1. var max int = 0
  2. /**
  3. * Definition for a binary tree node.
  4. * type TreeNode struct {
  5. * Val int
  6. * Left *TreeNode
  7. * Right *TreeNode
  8. * }
  9. */
  10. func findFrequentTreeSum(root *TreeNode) (res []int) {
  11. max = 0
  12. freq := make(map[int]int)
  13. postorder(root, &freq)
  14. for k, v := range freq {
  15. if v == max {
  16. res = append(res, k)
  17. }
  18. }
  19. return
  20. }
  21. func postorder(root *TreeNode, freq *map[int]int) int {
  22. if root == nil {
  23. return 0
  24. }
  25. l := postorder(root.Left, freq)
  26. r := postorder(root.Right, freq)
  27. sum := l + r + root.Val
  28. (*freq)[sum]++
  29. if max < (*freq)[sum] {
  30. max = (*freq)[sum]
  31. }
  32. return sum
  33. }