Last active
January 17, 2022 16:47
-
-
Save CollinShoop/b29477c1aed862f08199f4594bb58214 to your computer and use it in GitHub Desktop.
https://leetcode.com/problems/most-frequent-subtree-sum/ 4 ms, faster than 95.65%
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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