August's Box

Most Frequent Subtree Sum

Description

Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.

Examples 1
Input:

  5
 /  \
2   -3

return [2, -3, 4], since all the values happen only once, return all of them in any order.
Examples 2
Input:

  5
 /  \
2   -5

return [2], since 2 happens twice, however -5 only occur once.

Solution

题目的意思是:

以二叉树里的所有节点作为root的子二叉树称为subtree,这些subtree的所有节点之和称为subtree sum。现在需要统计所有子二叉树的subtree sum出现次数最多的root节点。

解法:
递归遍历所有二叉树,记录subtree sum和子树的和。代码如下:

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def findFrequentTreeSum(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
self.info.clear()
self.calFrequentInfo(root)
cnt = self.info[max(self.info, key=self.info.get)] if root else 0
return [key for key, val in self.info.items() if val == cnt]
info = collections.defaultdict(int)
def calFrequentInfo(self, root):
if not root:
return 0
value = root.val + self.calFrequentInfo(root.left) + self.calFrequentInfo(root.right)
self.info[value] += 1
return value

c++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
vector<int> findFrequentTreeSum(TreeNode* root) {
unordered_map<int, int> mp;
int maxCnt = 0;
vector<int> result;
calFrequentInfo(root, mp, maxCnt);
for(auto x : mp) {
if(x.second == maxCnt)
result.push_back(x.first);
}
return result;
}
int calFrequentInfo(TreeNode* root, unordered_map<int, int> &mp, int &maxCnt) {
if(!root) return 0;
int value = root->val + calFrequentInfo(root->left, mp, maxCnt) + calFrequentInfo(root->right, mp, maxCnt);
mp[value]++;
maxCnt = max(maxCnt, mp[value]);
return value;
}