【LeetCode】508. Most Frequent Subtree Sum 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/most-frequent-subtree-sum/description/
题目描述
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.
题目大意
先找出树的每个节点的值与所有子节点的和,然后找出和中出现频率最大的值。
解题方法
按照题目大意的思路,先进行求和遍历,找出所有的节点月其子节点的和,然后使用Counter()找出每个词的频率,返回出现频率最大的值即可。
注意哈,在getSum()函数中,别忘了返回当前求得的和,如果这个忘写了,那么返回的就是None.
Python解法如下:
# Definition for a binary tree node.
# 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 []
vals = []
def getSum(root):
if not root:
return 0
s = getSum(root.left) + root.val + getSum(root.right)
vals.append(s)
# 别忘了返回s
return s
getSum(root)
count = collections.Counter(vals)
frequent = max(count.values())
return [x for x, v in count.items() if v == frequent]
二刷的思路是这样的,对于每个节点都去一个函数求和,然后用dfs遍历每个节点。这样说来,时间复杂度略高。
统计出每个节点的和之后,需要用字典统计。
第一版代码C++如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> findFrequentTreeSum(TreeNode* root) {
dfs(root);
map<int, int> d;
int most_common = 0;
for (int s : sums) {
d[s] ++;
most_common = max(most_common, d[s]);
}
vector<int> res;
for (auto p : d){
if (p.second == most_common)
res.push_back(p.first);
}
return res;
}
private:
vector<int> sums;
void dfs(TreeNode* root) {
if (!root) return;
dfs(root->left);
sums.push_back(getSum(root));
dfs(root->right);
}
int getSum(TreeNode* root) {
if (!root) return 0;
int l = getSum(root->left);
int r = getSum(root->right);
return root->val + l + r;
}
};
然后稍加思索就发现,遍历了两次,所以可以把两个函数只保留一个,代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> findFrequentTreeSum(TreeNode* root) {
getSum(root);
vector<int> res;
for (auto p : d)
if (p.second == most_common)
res.push_back(p.first);
return res;
}
private:
vector<int> sums;
int most_common = 0;
map<int, int> d;
int getSum(TreeNode* root) {
if (!root) return 0;
int l = getSum(root->left);
int r = getSum(root->right);
int s = root->val + l + r;
sums.push_back(s);
d[s]++;
most_common = max(most_common, d[s]);
return s;
}
};
日期
2018 年 3 月 4 日
2018 年 12 月 13 日 —— 时间匆匆,如何才能提高时间利用率?
【LeetCode】508. Most Frequent Subtree Sum 解题报告(Python & C++)的更多相关文章
- [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 ...
- [leetcode]508. Most Frequent Subtree Sum二叉树中出现最多的值
遍历二叉树,用map记录sum出现的次数,每一个新的节点都统计一次. 遍历完就统计map中出现最多的sum Map<Integer,Integer> map = new HashMap&l ...
- 508. Most Frequent Subtree Sum 最频繁的子树和
[抄题]: Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum ...
- 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 ...
- 【LeetCode】829. Consecutive Numbers Sum 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 数学方法 日期 题目地址:https://leetc ...
- 【LeetCode】64. Minimum Path Sum 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
- 508 Most Frequent Subtree Sum 出现频率最高的子树和
详见:https://leetcode.com/problems/most-frequent-subtree-sum/description/ C++: /** * Definition for a ...
- LeetCode: Binary Tree Maximum Path Sum 解题报告
Binary Tree Maximum Path SumGiven a binary tree, find the maximum path sum. The path may start and e ...
- 【LeetCode】654. Maximum Binary Tree 解题报告 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcode ...
随机推荐
- 优化if else嵌套代码
写在前面 不知大家有没遇到过像"横放着的金字塔"一样的if else嵌套: if (true) { if (true) { if (true) { if (true) { if ( ...
- swift设置导航栏item颜色和状态栏颜色
//swift设置导航栏item颜色和状态栏颜色 let dict:Dictionary =[NSForegroundColorAttributeName:UIColor.hrgb("333 ...
- 3.7 rust 静态块
Cargo.toml [dependencies] lazy_static = "1.4.0" main.rs #[macro_use] extern crate lazy_sta ...
- RAC中常见的高级用法-bind方法
RAC操作思想: Hook(钩子)思想 RAC核心方法:bind bind方法 假设想监听文本框的内容,并且在每次输出结果的时候,都在文本框的内容拼接一段文字" ...
- redis入门到精通系列(一)
(一)为什么要用Nosql 如果你是计算机本科学生 ,那么一定使用过关系型数据库mysql.在请求量小的情况下,使用mysql不会有任何问题,但是一旦同时有成千上万个请求同时来访问系统时,就会出现卡顿 ...
- SpringMVC(1):SpringMVC入门
一,MVC 概述 MVC:模型,视图,控制器,是一种软件设计规范,本质是将业务逻辑,数据,显示,分离的方式来编写代码:前后端分离 Model:数据模型,提供要展示的数据,一般我们都会把这两个分离开来. ...
- Spring Cloud中使用Eureka
一.创建00-eurekaserver-8000 (1)创建工程 创建一个Spring Initializr工程,命名为00-eurekaserver-8000,仅导入Eureka Server依赖即 ...
- SQL错误总结
ORA-00918: column ambiguously defined 异常原因: select 查询的字段在from的两张表中都存在,导致数据库无法区别需要查询的字段来自于哪张表 以下是例子 s ...
- spring cloud config center Git SSH configuration
Git SSH configuration using properties By default, the JGit library used by Spring Cloud Config Serv ...
- Vue局部组件和全局组件
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...