作者: 负雪明烛
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++)的更多相关文章

  1. [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 ...

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

    遍历二叉树,用map记录sum出现的次数,每一个新的节点都统计一次. 遍历完就统计map中出现最多的sum Map<Integer,Integer> map = new HashMap&l ...

  3. 508. Most Frequent Subtree Sum 最频繁的子树和

    [抄题]: Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum ...

  4. 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 ...

  5. 【LeetCode】829. Consecutive Numbers Sum 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 数学方法 日期 题目地址:https://leetc ...

  6. 【LeetCode】64. Minimum Path Sum 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  7. 508 Most Frequent Subtree Sum 出现频率最高的子树和

    详见:https://leetcode.com/problems/most-frequent-subtree-sum/description/ C++: /** * Definition for a ...

  8. 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 ...

  9. 【LeetCode】654. Maximum Binary Tree 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcode ...

随机推荐

  1. 数据库命令补全工具mycli

    一.安装 我的数据库安装的是win版本,安装python后,直接命令行: 1 pip install mycli 即可. 二.使用 进入命令行后输入: 1 mycli -u root -p 88888 ...

  2. C/C++ Qt StatusBar 底部状态栏应用

    Qt窗体中默认会附加一个QstatusBar组件,状态栏组件位于主窗体的最下方,其作用是提供一个工具提示功能,当程序中有提示信息是可以动态的显示在这个区域内,状态栏组件内可以增加任何Qt中的通用组件, ...

  3. c#年份筛选

    年份: <script type="text/javascript" src="http://www.shicishu.com/down/WdatePicker.j ...

  4. addict, address, adequate.四级

    addict addiction – a biopsychosocial [生物社会心理学的 bio-psycho-social] disorder characterized by persiste ...

  5. IDEA中对代码进行测试

    一. 建立对应得目录 二.导入junit依赖 <dependency> <groupId>junit</groupId> <artifactId>jun ...

  6. Flume(三)【进阶】

    [toc] 一.Flume 数据传输流程 重要组件: 1)Channel选择器(ChannelSelector) ​ ChannelSelector的作用就是选出Event将要被发往哪个Channel ...

  7. listView 多布局

    最近在开发项目中遇到了实现类似淘宝首页的需求,使用listView可以解决,在此记录一下. 实现步骤: 重写 getViewTypeCount() – 返回你有多少个不同的布局 重写 getItemV ...

  8. mybatis-扩展

    分页插件 使用pageHelper参考官方https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse. ...

  9. RAC常见的宏

    1. RAC           作用:用来给某个对象的某个属性绑定信号,只要产生信号内容就会把内容给属性赋值            RAC(_label, text) = _textField.ra ...

  10. Java实现邮件收发

    一. 准备工作 1. 传输协议 SMTP协议-->发送邮件: 我们通常把处理用户smtp请求(邮件发送请求)的服务器称之为SMTP服务器(邮件发送服务器) POP3协议-->接收邮件: 我 ...