考点 | 难度 |
---|---|
DFS | Medium |
Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.
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).
用hashmap储存sum出现的次数,DFS所有subtree
class Solution:
def findFrequentTreeSum(self, root):
if root is None: return []
def dfs(node):
if node is None: return 0
s = node.val + dfs(node.left) + dfs(node.right)
count[s] += 1
return s
count = collections.Counter()
dfs(root)
maxCount = max(count.values())
return [s for s in count if count[s] == maxCount]