作者: 负雪明烛
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. 55. Binary Tree Preorder Traversal

    Binary Tree Preorder Traversal My Submissions QuestionEditorial Solution Total Accepted: 119655 Tota ...

  2. nginx 的一个conf配置

    server { listen 80 default_server; server_name www.caipudq.cn caipudq.cn *.caipudq.cn; root /mnt/www ...

  3. LATEX公式语法

    see how any formula was written in any question or answer, including this one, right-click on the ex ...

  4. javaSE高级篇2 — 流技术 — 更新完毕

    1.先认识一个类----File类 前言:IO相关的一些常识 I / O----输入输出 I     输入     input 0    输出     output I / o 按数据的流动方向来分- ...

  5. 巩固javaweb的第二十七天

    巩固内容 正则表达式: 5. 指定字符串的开始和结尾 正则表达式中字符串的开始和结束符如表 2.6 所示. 表 2.6 开 始 和 结 尾 字符 作 用 ^ 指定以某个字符串开始 $ 指定以某个字符串 ...

  6. day06 模板层

    day06 模板层 今日内容 常用语法 模板语法传值 模板语法之过滤器 模板语法之标签 自定义过滤器.标签.inclusion_tag(BBS作业用一次) 模板的继承(django前后端结合 那么使用 ...

  7. day08 Nginx模块

    day08 Nginx模块 lnmp架构 l :Linux n :Nginx m :MySQL p :Python/PHP lnmp架构:是最简单的架构 Nginx中的模块(Python模块):前提是 ...

  8. ALitum技巧

    创建异型焊盘的方法 SCH与PCB同步修改后元器件乱跑的解决方法 Altium 在PCB重新编号更新到SCH原理图的方法 同步问题 其他技巧: 当前层亮色,其他层灰色切换:SHIFT+S

  9. 【Python】【Basic】【数据类型】运算符与深浅拷贝

    运算符   1.算数运算: 2.比较运算: 3.赋值运算: 4.逻辑运算: 5.成员运算: 三元运算 三元运算(三目运算),是对简单的条件语句的缩写. # 书写格式 result = 值1 if 条件 ...

  10. String.split()与StringUtils.split()的区别

    import com.sun.deploy.util.StringUtils; String s =",1,,2,3,4,,"; String[] split1 = s.split ...