作者: 负雪明烛
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. BeautifulSoup解析库的介绍和使用

    ### BeautifulSoup解析库的介绍和使用 ### 三大选择器:节点选择器,方法选择器,CSS选择器 ### 使用建议:方法选择器 > CSS选择器 > 节点选择器 ## 测试文 ...

  2. Mssql主备见证的弊端及主备模式主down掉怎么恢复

    mssql主备见证有个没有解决的问题,mssql的主备是针对单个库的,有时候单个或多个库主备切换了,但是整个主数据库并没有挂掉,并且还运行着其他的库,程序检测到的数据库连接是正常的,只是部分库连接不了 ...

  3. Spring Security 基于URL的权限判断

    1.  FilterSecurityInterceptor 源码阅读 org.springframework.security.web.access.intercept.FilterSecurityI ...

  4. 学习Java的第三天

    一.今日收获 1.今天家里有白事,忙了一整天,也没有看更多的资料 二.今日问题 无 三.明日目标 补全今天耽误的功课,继续学习java!

  5. nuxt.js相关随笔

    对于nuxt.js从未接触,对于项目需要进行零散了解,作此归纳,以下都是一个新手的拙见与理解,有不同意见欢迎提出,但请勿喷. 一.项目创建 npx create-nuxt-app projectNam ...

  6. addict, address, adequate.四级

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

  7. @Data 注解引出的 lombok

    今天在看代码的时候, 看到了这个注解, 之前都没有见过, 所以就查了下, 发现还是个不错的注解, 可以让代码更加简洁. 这个注解来自于 lombok,lombok 能够减少大量的模板代码,减少了在使用 ...

  8. Cnblog博客美化

    具体的使用教程文档在这里 BNDong/Cnblogs-Theme-SimpleMemory 简要的操作如下: 博客园 - 管理 - 设置 值得注意得是: 要想JS代码要申请才可以使用 博客侧边栏 可 ...

  9. JSP常用内置对象

    1.request 1.1getAttribute(String name) 2.getAttributeName() 3.getCookies() 4.getCharacterEncoding() ...

  10. Java如何生成随机数 - Random、ThreadLocalRandom、SecureRandom

    Java7 的Random伪随机数和线程安全的ThreadLocalRandom 一.Random伪随机数: Random 类专门用于生成一个伪随机数,它有两个构造器: 一个构造器使用默认的种子(以当 ...