LeetCode | 0508. 出现次数最多的子树元素和【Python】

Problem

LeetCode

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:

  5
/  \
2   -3


return [2, -3, 4], since all the values happen only once, return all of them in any order.

Examples 2
Input:

  5
/  \
2   -5


return [2], since 2 happens twice, however -5 only occur once.

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

问题

  5
/  \
2   -3


  5
/  \
2   -5


思路

DFS

先思考每一个节点需要做的事：该节点值与左右子树的所有节点值相加。



Python3 代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
import collections
res_dic = collections.defaultdict(int)
# 计算子树元素和
def dfs(node):
# 递归边界
if not node:
return 0
tmp_sum = dfs(node.left) + node.val + dfs(node.right)
res_dic[tmp_sum] += 1
return tmp_sum

if not root:
return []
dfs(root)
max_cnt = 0
for cnt in res_dic.values():
max_cnt = max(max_cnt, cnt)
return [key for key, cnt in res_dic.items() if cnt == max_cnt]


Python

08-09 665
03-18 267
01-18 650
11-15 28
11-15 159
03-05 266