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:

1
2
3
5
/ \
2 -3

Examples 2
Input:

1
2
3
5
/ \
2 -5

Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer.

思路

最下方的sum函数的作用就是递归地求出该节点下子树的和。居然在这个地方卡了很久【捂脸】

接下来,我们从根节点开始进行递归,求出每一个节点的子树和。我们把每一个节点的和它的子树和当作一个键值对,放进哈希表当中,从而可以统计出题意所需的众数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findFrequentTreeSum(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if (root):
sums = []
self.helper(root, sums)
count = {}
for s in sums:
if count.has_key(s):
count[s] += 1
else:
count[s] = 1
maximum = max(count.values())
ans = []
for i in count:
if (count[i] == maximum):
ans.append(i)
return ans
else:
return []
def helper(self, root, sums):
sums.append(self.sumtree(root))
if (root.left):
self.helper(root.left, sums)
if (root.right):
self.helper(root.right, sums)
def sumtree(self, root):
if not root:
return 0
else:
return self.sumtree(root.right) + self.sumtree(root.left) + root.val