-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathMostFrequentSubtreeSum.py
50 lines (41 loc) · 1.42 KB
/
MostFrequentSubtreeSum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# -*- coding: utf-8 -*-
# @File : MostFrequentSubtreeSum.py
# @Date : 2020-03-04
# @Author : tc
"""
题号 508. 出现次数最多的子树元素和
给出二叉树的根,找出出现次数最多的子树元素和。一个结点的子树元素和定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。然后求出出现次数最多的子树元素和。如果有多个元素出现的次数相同,返回所有出现次数最多的元素(不限顺序)。
示例 1
输入:
5
/ \
2 -3
返回 [2, -3, 4],所有的值均只出现一次,以任意顺序返回所有值。
示例 2
输入:
5
/ \
2 -5
返回 [2],只有 2 出现两次,-5 只出现 1 次。
参考:https://leetcode.com/problems/most-frequent-subtree-sum/discuss/98675/JavaC%2B%2BPython-DFS-Find-Subtree-Sum
"""
from typing import List
import collections
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
if not root: return []
def dfs(node):
if not node:
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]