标签: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