# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = NoneclassSolution(object):deffindFrequentTreeSum(self,root):""" https://leetcode.com/problems/most-frequent-subtree-sum/description/ :type root: TreeNode :rtype: List[int] """ di ={}defrecurse(root):if root ==None:return0 su = root.val +recurse(root.left)+recurse(root.right)if su notin di: di[su]=0 di[su]+=1return surecurse(root) re, ma = [],0for i in di:if di[i]> ma: re = [i] ma = di[i]elif di[i]== ma: re.append(i)return re
We will recursively calculate the sums for each subtree, and keep a dictionary to keep track of the number of times a sum has occurred. Then we can just iterate through the list and return the list of those values that occur maximum number of times
Time Complexity:O(N), where N is the total number of nodes