[LeetCode]508. Most Frequent Subtree Sum

题目

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

方法

对二叉树进行后续遍历,递归实现,将node节点及其子节点的和保存为nodeval,最后就能获取所有node及其子节点和。将各个node子节点和及其出现次数保存在dict中,最后选出出现次数最多的子节点和。

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]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,767评论 0 33
  • 秋姑娘不知不觉来到了人间,树叶们一起演奏着交响曲,欢迎秋姐姐的到来。 秋姑娘伞下缠绵的秋雨,滋润着小草,让小草有了...
    执工作室_小蝶阅读 323评论 0 0
  • 今天天气很寒冷,但是人最怕的不是身体上遇到的寒流,而是在精神上,别人对你的寒冷。最近我在反思,到底人遇到了让自己...
    优雅小姐Zoe阅读 215评论 0 1