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.

这道题给了我们一个二叉树,让我们求出现频率最高的子树之和,求树的结点和并不是很难,就是遍历所有结点累加起来即可。那么这道题的暴力解法就是遍历每个结点,对于每个结点都看作子树的根结点,然后再遍历子树所有结点求和,这样也许可以通过 OJ,但是绝对不是最好的方法。我们想下子树有何特点,必须是要有叶结点,单独的一个叶结点也可以当作是子树,那么子树是从下往上构建的,这种特点很适合使用后序遍历,我们使用一个 HashMap 来建立子树和跟其出现频率的映射,用一个变量 cnt 来记录当前最多的次数,递归函数返回的是以当前结点为根结点的子树结点值之和,然后在递归函数中,我们先对当前结点的左右子结点调用递归函数,然后加上当前结点值,然后更新对应的 HashMap 中的值,然后看此时 HashMap 中的值是否大于等于 cnt,大于的话首先要清空 res,等于的话不用,然后将 sum 值加入结果 res 中即可,参见代码如下:

解法一:

class Solution {
public:
vector<int> findFrequentTreeSum(TreeNode* root) {
vector<int> res;
unordered_map<int, int> m;
int cnt = ;
postorder(root, m, cnt, res);
return res;
}
int postorder(TreeNode* node, unordered_map<int, int>& m, int& cnt, vector<int>& res) {
if (!node) return ;
int left = postorder(node->left, m, cnt, res);
int right = postorder(node->right, m, cnt, res);
int sum = left + right + node->val;
++m[sum];
if (m[sum] >= cnt) {
if (m[sum] > cnt) res.clear();
res.push_back(sum);
cnt = m[sum];
}
return sum;
}
};

下面这种解法跟上面的基本一样,就是没有在递归函数中更新结果 res,更是利用 cnt,最后再更新 res,这样做能略微高效一些,参见代码如下:

解法二:

class Solution {
public:
vector<int> findFrequentTreeSum(TreeNode* root) {
vector<int> res;
unordered_map<int, int> m;
int cnt = ;
postorder(root, m, cnt);
for (auto a : m) {
if (a.second == cnt) res.push_back(a.first);
}
return res;
}
int postorder(TreeNode* node, unordered_map<int, int>& m, int& cnt) {
if (!node) return ;
int left = postorder(node->left, m, cnt);
int right = postorder(node->right, m, cnt);
int sum = left + right + node->val;
cnt = max(cnt, ++m[sum]);
return sum;
}
};

开始我还在想能不能利用后序遍历的迭代形式来解,后来想了半天发现不太容易实现,因为博主无法想出有效的机制来保存左子树结点之和,而计算完对应的右子树结点之和后要用到对应的左子树结点之和,才能继续往上算。可能博主不够 smart,有大神如果知道如何用迭代的形式来解,请一定要留言告知博主啊,多谢啦~

Github 同步地址:

https://github.com/grandyang/leetcode/issues/508

类似题目:

Subtree of Another Tree

参考资料:

https://leetcode.com/problems/most-frequent-subtree-sum/

https://leetcode.com/problems/most-frequent-subtree-sum/discuss/98675/JavaC%2B%2BPython-DFS-Find-Subtree-Sum

https://leetcode.com/problems/most-frequent-subtree-sum/discuss/98664/Verbose-Java-solution-postOrder-traverse-HashMap-(18ms)

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 508. Most Frequent Subtree Sum 出现频率最高的子树和的更多相关文章

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

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

  2. [LeetCode] 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 ...

  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. [leetcode]508. Most Frequent Subtree Sum二叉树中出现最多的值

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

  5. 【LeetCode】508. Most Frequent Subtree Sum 解题报告(Python & C++)

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

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

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

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

  9. [Swift]LeetCode508. 出现次数最多的子树元素和 | 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 ...

随机推荐

  1. ICP 匹配定位算法学习记录

    icp 算法原理是: 选取目标点云P和源点云Q,按照一定的约束条件,找到最邻近点(pi,qi),然后计算出最优R和t(旋转和平移), 使得误差函数最小,误差函数E(R,t): 基本算法流程: 1.在目 ...

  2. Centos7安装percona-xtrabackup2.4和8.0版本

    Percona XtraBackup是一个基于MySQL的服务器的开源热备份实用程序 ,它不会在备份期间锁定您的数据库.无论是24x7高负载服务器还是低事务量环境,Percona XtraBackup ...

  3. python threading ThreadPoolExecutor源码解析

    future: 未来对象,或task的返回容器 1. 当submit后: def submit(self, fn, *args, **kwargs): with self._shutdown_lock ...

  4. SimdJsonSharp:每秒解析千兆字节的JSON

    SimdJsonSharp: Parsing gigabytes of JSON per second C# version of lemire/simdjson (by Daniel Lemire ...

  5. LaTex语法

    排版数学公式是TeX系统设计的初衷,它在LaTeX中占有特殊地位,也是LaTeX最为人所称道的功能之一.基于对MathType排版效果的不满意,以及对公式进行检索的需求,我们使用LaTeX输入数学公式 ...

  6. 自然语言处理(NLP) - 数学基础(3) - 概率论基本概念与随机事件

    好像所有讲概率论的文章\视频都离不开抛骰子或抛硬币这两个例子, 因为抛骰子的确是概率论产生的基础, 赌徒们为了赢钱就不在乎上帝了才导致概率论能突破宗教的绞杀, 所以我们这里也以抛骰子和抛硬币这两个例子 ...

  7. C# vb .NET生成QR二维码

    二维码比条形码具有更多优势,有些场合使用二维码比较多,比如支付.通过将某些数据生成二维码,就可以实现一码走天下.那么如何在C#,.Net平台代码里生成二维码呢?答案是使用SharpBarcode! S ...

  8. 自己动手搭建经典的3层 Asp.Net MVC

    1:IBaseDAL using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expr ...

  9. OpenCV.Net基于傅里叶变换进行文本的旋转校正

    本文描述一种利用OpenCV及傅里叶变换识别图片中文本旋转角度并自动校正的方法,由于对C#比较熟,因此本文将使用OpenCVSharp. 文章参考了http://johnhany.net/2013/1 ...

  10. JavaScript RegExp(正则表达式) 对象

    正则表达式是描述字符模式的对象.正则表达式用于在文本上执行模式匹配和“搜索和替换”功能. var patt = /JC2182/i 示例说明: /JC2182/i - 是一个正则表达式. JC2182 ...