当前位置:网站首页>LeetCode 508. The most frequent subtree elements and
LeetCode 508. The most frequent subtree elements and
2022-07-03 09:01:00 【Sasakihaise_】
508. The most frequent sub tree elements and
【DFS】DFS Used in the process of map Record the subtree and the number of occurrences , Traverse map Find the most frequent occurrences .
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
// 12:47 6
public Map<Integer, Integer> map;
public int dfs(TreeNode root){
if(root == null) return 0;
int left = dfs(root.left);
int right = dfs(root.right);
int sum = root.val + left + right;
map.put(sum, map.getOrDefault(sum, 0) + 1);
return sum;
}
public int[] findFrequentTreeSum(TreeNode root) {
map = new HashMap();
dfs(root);
int max = 0;
List<Integer> list = new ArrayList();
for(var k: map.keySet()){
if(map.get(k) > max){
list.clear();
list.add(k);
max = map.get(k);
}else if(map.get(k) == max){
list.add(k);
}
}
int[] ans = new int[list.size()];
int i = 0;
for(var j: list) ans[i++] = j;
return ans;
}
}
边栏推荐
- Slice and index of array with data type
- Alibaba canaladmin deployment and canal cluster Ha Construction
- Binary tree traversal (first order traversal. Output results according to first order, middle order, and last order)
- LeetCode 513. 找树左下角的值
- Solution of 300ms delay of mobile phone
- [concurrent programming] collaboration between threads
- 22-06-27 西安 redis(01) 安装redis、redis5种常见数据类型的命令
- Use of sort command in shell
- 状态压缩DP AcWing 291. 蒙德里安的梦想
- JS ternary operator - learning notes (with cases)
猜你喜欢
Slice and index of array with data type
Parameters of convolutional neural network
Query XML documents with XPath
推荐一个 yyds 的低代码开源项目
Es8 async and await learning notes
分配异常的servlet
Notes and bugs generated during the use of h:i:s and y-m-d
Deep parsing (picture and text) JVM garbage collector (II)
AcWing 787. 归并排序(模板)
XPath实现XML文档的查询
随机推荐
高斯消元 AcWing 883. 高斯消元解线性方程组
22-06-28 西安 redis(02) 持久化机制、入门使用、事务控制、主从复制机制
[rust notes] 12 closure
The difference between if -n and -z in shell
[concurrent programming] concurrent tool class of thread
教育信息化步入2.0,看看JNPF如何帮助教师减负,提高效率?
注解简化配置与启动时加载
Slice and index of array with data type
传统企业数字化转型需要经过哪几个阶段?
What is the difference between sudo apt install and sudo apt -get install?
Alibaba canal actual combat
Mortgage Calculator
LeetCode 30. 串联所有单词的子串
How to use Jupiter notebook
一个优秀速开发框架是什么样的?
createjs easeljs
Annotations simplify configuration and loading at startup
The method for win10 system to enter the control panel is as follows:
分配异常的servlet
浅谈企业信息化建设