Skip to content

Instantly share code, notes, and snippets.

@CollinShoop
Last active January 17, 2022 16:47
Show Gist options
  • Save CollinShoop/b29477c1aed862f08199f4594bb58214 to your computer and use it in GitHub Desktop.
Save CollinShoop/b29477c1aed862f08199f4594bb58214 to your computer and use it in GitHub Desktop.
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findFrequentTreeSum(root *TreeNode) []int {
counts := map[int]int{}
var countSum func(node *TreeNode) int
countSum = func(node *TreeNode) int {
if node == nil {
return 0
}
var treeSum = node.Val + countSum(node.Left) + countSum(node.Right)
counts[treeSum]++
return treeSum
}
countSum(root)
frequentCounts := []int{}
highestFreq := 0
for count, freq := range counts {
if freq > highestFreq {
frequentCounts = []int{count}
highestFreq = freq
} else if freq == highestFreq {
frequentCounts = append(frequentCounts, count)
}
}
return frequentCounts
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment