当前位置:网站首页>[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;
}
边栏推荐
- 专题教程——选队长游戏
- Go from entry to practice - multiple selection and timeout control (notes)
- DO280OpenShift访问控制--security policy和章节实验
- Save method of JPA stepping pit series
- 畅游动态规划之区间DP
- GBase 8a的create database 会被查询耗时很长怀疑卡住的现象分析
- Common methods of string class
- Go从入门到实战——channel的关闭和广播(笔记)
- 数组作业题
- SQL必需掌握的100个重要知识点:IN 操作符
猜你喜欢

CORBA 架构体系指南(通用对象请求代理体系架构)

关于异常处理的知识整理

100 important knowledge points that SQL must master: filtering data

Go from introduction to practice -- coordination mechanism (note)

Go from introduction to practice - Interface (notes)

A set of system to reduce 10 times the traffic pressure in crowded areas

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

强制 20 天内开发 APP 后集体被裁,技术负责人怒批:祝“早日倒闭!”

抖音的兴趣电商已经碰到流量天花板?

Yu Wenwen, Hu Xia and other stars take you to play with the party. Pipi app ignites your summer
随机推荐
Quick excel export
互联网 35~40 岁的一线研发人员,对于此岗位的核心竞争力是什么?
How to participate in openharmony code contribution
Go from introduction to practice - Interface (notes)
鲜为人知的mysql导入数据
集合代码练习
String类的常用方法
Burp suite遇到的常见问题
SQL必需掌握的100个重要知识点:过滤数据
IO stream code
Go从入门到实战——所有任务完成(笔记)
qt 大文件生成md5校验码
猜拳游戏专题训练
开源技术交流丨一站式全自动化运维管家ChengYing入门介绍
Quick excel export according to customized excel Title Template
Have time to look at ognl expressions
富文本 考试 填空题
快速excel导出
Codeforces Round #721 (Div. 2)
Go从入门到实战——错误机制(笔记)