Leetcode 508. Most Frequent Subtree Sum

Posted 周洋的Blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 508. Most Frequent Subtree Sum相关的知识,希望对你有一定的参考价值。

递归.

注意:collections.Counter()有一个most_common()函数,比较实用.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def __init__(self):
        self.used={}
    def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
        if not root:
            return []
        num=[]
        stack=[root]
        while stack:
            node=stack.pop()
            if self.used.get(node,False)!=False:
                num.append(self.used[node])
            else:
                num.append(self.tree_sum(node))
            if node.right:
                stack.append(node.right)
            if node.left:
                stack.append(node.left)
        count=collections.Counter(num)
        most=count.most_common()
        ans=[most[0][0]]
        if len(most)>1:
            for m in most[1:]:
                if m[1]==most[0][1]:
                    ans.append(m[0])
                else:
                    break
        return ans
        
    def tree_sum(self,node:TreeNode)->int:
        if not node:
            return 0
        if self.used.get(node,False)!=False:
            return self.used[node]
        ans= node.val+self.tree_sum(node.left)+self.tree_sum(node.right)
        self.used[node]=ans
        return ans

 

以上是关于Leetcode 508. Most Frequent Subtree Sum的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 508. Most Frequent Subtree Sum

Leetcode508 Most Frequent Subtree Sum

[leetcode]508. Most Frequent Subtree Sum二叉树中出现最多的值

508. Most Frequent Subtree Sum

508. Most Frequent Subtree Sum (Medium)

508. Most Frequent Subtree Sum