当前位置:网站首页>[LeetCode]508. The most frequent subtree elements and
[LeetCode]508. The most frequent subtree elements and
2022-06-27 21:50:00 【A Fei algorithm】
subject
508. The most frequent sub tree elements and
Give you a root node of binary tree root , Please return the most frequent subtree elements and . If more than one element appears the same number of times , Returns all the most frequent subtree elements and ( Unlimited order ).
Of a node 「 Subtree elements and 」 It is defined as the sum of the elements of all nodes in the binary tree with the node as the root ( Including the node itself ).
Example 1:
Input : root = [5,2,-3]
Output : [2,-3,4]
Example 2:
Input : root = [5,2,-5]
Output : [2]
Tips :
The number of nodes is [1, 104] Within the scope of
-105 <= Node.val <= 105
Method 1:DFS
public int[] findFrequentTreeSum(TreeNode root) {
if (root == null) return new int[]{
};
dfs(root);
List<Integer> list = new ArrayList<>();
for (int k : map.keySet()) {
if (map.get(k) == maxx) list.add(k);
}
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) res[i] = list.get(i);
return res;
}
int maxx = 0;// Maximum number of occurrences
// Record the current occurrence of sum The number of times
Map<Integer, Integer> map = new HashMap<>();
private int dfs(TreeNode root) {
if (root == null) return 0;
int l = dfs(root.left);
int r = dfs(root.right);
int s = l + root.val + r;
map.put(s, map.getOrDefault(s, 0) + 1);
maxx = Math.max(maxx, map.get(s));
return s;
}
边栏推荐
- 快递e栈——数组篇小型项目
- Burp suite遇到的常见问题
- Go from starting to Real - Interface (note)
- Knowledge sorting of exception handling
- What is the core competitiveness of front-line R & D personnel aged 35~40 in this position?
- [LeetCode]186. 翻转字符串里的单词 II
- SQL必需掌握的100个重要知识点:组合 WHERE 子句
- 根据自定义excel标题模板快速excel导出
- 本周二晚19:00战码先锋第8期直播丨如何多方位参与OpenHarmony开源贡献
- DO280OpenShift访问控制--security policy和章节实验
猜你喜欢

Go from introduction to actual combat - context and task cancellation (notes)

让马化腾失望了!Web3.0,毫无希望

.NET学习笔记(五)----Lambda、Linq、匿名类(var)、扩展方法

Save method of JPA stepping pit series

Go从入门到实战——Context与任务取消(笔记)

Go从入门到实战——仅执行一次(笔记)

开源技术交流丨一站式全自动化运维管家ChengYing入门介绍

Go from starting to Real - Interface (note)

SQL必需掌握的100个重要知识点:使用函数处理数据

Go从入门到实战——行为的定义和实现(笔记)
随机推荐
富文本 考试 填空题
Codeforces Round #723 (Div. 2)
Go从入门到实战——依赖管理(笔记)
Go从入门到实战——行为的定义和实现(笔记)
matlab查找某一行或者某一列在矩阵中的位置
Go from entry to practice -- CSP concurrency mechanism (note)
Go从入门到实战——package(笔记)
有时间看看ognl表达式
Knowledge sorting of exception handling
Go从入门到实战——CSP并发机制(笔记)
Go從入門到實戰——接口(筆記)
本周二晚19:00战码先锋第8期直播丨如何多方位参与OpenHarmony开源贡献
100 important knowledge points that SQL must master: combining where clauses
Go从入门到实战——任务的取消(笔记)
How to delete "know this picture" on win11 desktop
Go从入门到实战——channel的关闭和广播(笔记)
语言弱点列表--CWE,一个值得学习的网站
Oracle migration MySQL unique index case insensitive don't be afraid
The difference between scrum and Kanban
AI painting minimalist tutorial