[LeetCode]Most Frequent Subtree Sum

题目描述:

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.

题目大意:

给定一棵二叉树,求其最频繁子树和。即所有子树的和中,出现次数最多的数字。如果存在多个次数一样的子树和,则全部返回。

注意:你可以假设任意子树和均为32位带符号整数。

解题思路:

树的遍历 + 计数

Python代码:

# Definition for a binary tree node.
# 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]
        """
        cnt = collections.Counter()
        def subTreeSum(root):
            if not root: return 0
            return root.val + subTreeSum(root.left) + subTreeSum(root.right)
        def traverse(root):
            if not root: return
            cnt[subTreeSum(root)] += 1
            traverse(root.left)
            traverse(root.right)
        traverse(root)
        maxfreq = max(cnt.values() + [None])
        return [e for e, v in cnt.iteritems() if v == maxfreq]

 

本文链接:http://bookshadow.com/weblog/2017/02/05/leetcode-most-frequent-subtree-sum/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论