[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]508. Most Frequent Subtree Sum)