码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 508. Most Frequent Subtree Sum

时间:2019-04-23 09:40:07      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:com   roo   ret   tco   break   app   比较   bsp   node   

递归.

注意: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

标签:com   roo   ret   tco   break   app   比较   bsp   node   

原文地址:https://www.cnblogs.com/zywscq/p/10754196.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!