/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ funcfindFrequentTreeSum(root *TreeNode)(ans []int) { treeSum := make(map[int]int) // missing len argument to make([]int) // ans := make([]int)
// [0,0,0,0,0,0,0,0,0,0] // ans := make([]int, 10) // ans := make([]int, 0) maxCnt := 0 // cannot use dummyNode (type leetcode.TreeNode) as type *leetcode.TreeNode in argument to dfsGetSum // dummyNode := TreeNode{ // dummyNode := &TreeNode{ // // unexpected =, expecting comma or } // // Left = root // Left: root, // } // dfsGetSum(treeSum, dummyNode, maxCnt) dfsGetSum(treeSum, root, &maxCnt) for k, v := range treeSum { if v == maxCnt { ans = append(ans, k) } } return }
funcfindFrequentTreeSum(root *TreeNode)(ans []int) { cnt := map[int]int{} maxCnt := 0 var dfs func(*TreeNode)int dfs = func(node *TreeNode)int { if node == nil { return0 } sum := node.Val + dfs(node.Left) + dfs(node.Right) cnt[sum]++ if cnt[sum] > maxCnt { maxCnt = cnt[sum] } return sum } dfs(root)
for s, c := range cnt { if c == maxCnt { ans = append(ans, s) } } return } // 链接:https://leetcode.cn/problems/most-frequent-subtree-sum/solution/chu-xian-ci-shu-zui-duo-de-zi-shu-yuan-s-kdjc/