博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
508. Most Frequent Subtree Sum (Medium)
阅读量:4676 次
发布时间:2019-06-09

本文共 1597 字,大约阅读时间需要 5 分钟。

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.

题意:对于给定的一棵二叉树,找出现频率最高的子树之和。

思路:遍历和collections.Counter()计数器

 

# Definition for a binary tree node.# class TreeNode():#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution():    def findFrequentTreeSum(self, root):        """        :type root: TreeNode        :rtype: List[int]        """        cnt = collections.Counter()                def sumOfSubTree(root):            if not root:                return 0            return root.val + sumOfSubTree(root.left) + sumOfSubTree(root.right)                def traverseTree(root):            if not root:                return None            cnt[sumOfSubTree(root)] += 1            traverseTree(root.left)            traverseTree(root.right)        traverseTree(root)        max_sum = max(cnt.values() + [None])        return [e for e, v in cnt.iteritems() if v == max_sum]
 

转载于:https://www.cnblogs.com/yancea/p/7563526.html

你可能感兴趣的文章
[转]B树(多向平衡查找树)详解
查看>>
ORACLE表、表分区、表空间的区别
查看>>
Windows7系统运行hadoop报Failed to locate the winutils binary in the hadoop binary path错误
查看>>
Arcgis 10.1安装
查看>>
关机时长时间停留在”正在保存设置“的解决办法
查看>>
vue使用video.js解决m3u8视频播放格式
查看>>
Ubuntu下配置使用maven
查看>>
常用sql语句
查看>>
13.无名管道通讯编程
查看>>
Kendo UI grid 表格数据更新
查看>>
js获取页面宽度给JS div设宽度
查看>>
如何恢复IIS出厂默认设置
查看>>
17.11.09
查看>>
在浏览器里友好的变量输出查看函数方法
查看>>
Excel中复杂跨行跨列数据
查看>>
day26
查看>>
房子过户给子女哪种方式最合适?买卖?赠与?继承?不看就亏大了!
查看>>
WinForm 生产环境、测试环境 多配置-App.config(分享)
查看>>
Java Garbage Collection基础详解------Java 垃圾回收机制技术详解
查看>>
SQL 中的函数
查看>>