作者: 负雪明烛
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. 【模板】Splay(伸展树)普通平衡树(数据加强版)/洛谷P6136

    题目链接 https://www.luogu.com.cn/problem/P6136 题目大意 需要写一种数据结构,来维护一些非负整数( \(int\) 范围内)的升序序列,其中需要提供以下操作: ...

  2. JavaScript获取html表单值验证后跳转网页中的关键点

    关键代码: 1.表单部分 <form action="Depart.jsp" name="myform" method="post" ...

  3. idea 启动debug的时候throw new ClassNotFoundException(name)

    idea 启动debug的时候throw new ClassNotFoundException(name) 启动debug就跳转到此界面 解决办法 这个方法只是忽略了抛异常的点,并没有真正解决问题.后 ...

  4. SQLyog连接mysql8报2058错误

    连接会话时,报如下错误. 通过网上查解决办法,报这个错误的原因是mysql密码加密方法变了 解决办法: 1.先使用mysql -uroot -p输入密码进去mysql 2.ALTER USER 'ro ...

  5. 25. Linux下gdb调试

    1.什么是core文件?有问题的程序运行后,产生"段错误 (核心已转储)"时生成的具有堆栈信息和调试信息的文件. 编译时需要加 -g 选项使程序生成调试信息: gcc -g cor ...

  6. 转 关于HttpClient,HttpURLConnection,OkHttp的用法

    转自:https://www.cnblogs.com/zp-uestc/p/10371012.html 1 HttpClient入门实例 1.1发送get请求 1 2 3 4 5 6 7 8 9 10 ...

  7. jenkins之代码部署回滚脚本

    #!/bin/bash DATE=`date +%Y-%m-%d_%H-%M-%S` METHOD=$1 BRANCH=$2 GROUP_LIST=$3 function IP_list(){ if ...

  8. spring 事务处理中,同一个类中:A方法(无事务)调B方法(有事务),事务不生效问题

    public class MyEntry implements IBaseService{ public String A(String jsonStr) throws Exception{ User ...

  9. centos 7 zookeeper 单体和集群搭建

    1.操作相关命令 1.0  安装命令     wget  :下载解压包 tar -xzvf  :解压 1.1  创建节点 create  / node : 创建一个名字为node的 空节点 creat ...

  10. C++STL标准库学习笔记(四)multiset续

    自定义排序规则的multiset用法 前言: 在这个笔记中,我把大多数代码都加了注释,我的一些想法和注解用蓝色字体标记了出来,重点和需要关注的地方用红色字体标记了出来,只不过这一次的笔记主要是我的补充 ...