【 Reference resources :508. The most frequent sub tree elements and - Power button (LeetCode)】
Write variables and functions like classes
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.cnt=Counter()
def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
self.dfs(root)
maxNum=max(self.cnt.values())
res=[k for k,v in self.cnt.items() if v==maxNum ]
return res
def dfs(self,root):
if root is None:return 0
left=self.dfs(root.left)
right=self.dfs(root.right)
he= root.val + left + right
self.cnt[he]+=1
return he
Write the required function inside the function
class Solution:
def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
cnt = Counter()
def dfs(node: TreeNode) -> int:
if node is None:
return 0
sum = node.val + dfs(node.left) + dfs(node.right)
cnt[sum] += 1
return sum
dfs(root) # Call below function
maxCnt = max(cnt.values())
return [s for s, c in cnt.items() if c == maxCnt]