題目
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.
難度
Medium
方法
對(duì)二叉樹(shù)進(jìn)行后續(xù)遍歷存谎,遞歸實(shí)現(xiàn),將node
節(jié)點(diǎn)及其子節(jié)點(diǎn)的和保存為node
的val
既荚,最后就能獲取所有node
及其子節(jié)點(diǎn)和。將各個(gè)node
子節(jié)點(diǎn)和及其出現(xiàn)次數(shù)保存在dict
中恰聘,最后選出出現(xiàn)次數(shù)最多的子節(jié)點(diǎn)和吸占。
python代碼
import collections
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def findFrequentTreeSum(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
self.counter = collections.Counter()
self.postOrderTraverse(root)
maxValue = max(self.counter.values())
return [key for key in self.counter.keys() if self.counter[key] == maxValue]
def postOrderTraverse(self, node):
if node.left:
node.val += self.postOrderTraverse(node.left)
if node.right:
node.val += self.postOrderTraverse(node.right)
self.counter[node.val] += 1
return node.val
root = TreeNode(5)
root.left = TreeNode(2)
root.right = TreeNode(-3)
assert Solution().findFrequentTreeSum(root) == [2, 4, -3]
root = TreeNode(5)
root.left = TreeNode(2)
root.right = TreeNode(-5)
assert Solution().findFrequentTreeSum(root) == [2]