【參考:508. 出現次數最多的子樹元素和 - 力扣(LeetCode)】
像類一樣寫變量和函數
# 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
把需要的函數寫在函數內部
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) # 在函數下方調用
maxCnt = max(cnt.values())
return [s for s, c in cnt.items() if c == maxCnt]