当前位置:网站首页>LeetCode 508. 出现次数最多的子树元素和
LeetCode 508. 出现次数最多的子树元素和
2022-07-03 08:49:00 【Sasakihaise_】
【DFS】DFS的过程中用map记录子树和已经出现次数,遍历map找出现次数最多即可。
/**
* 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;
}
}
边栏推荐
- [rust notes] 13 iterator (Part 1)
- The method of replacing the newline character '\n' of a file with a space in the shell
- Common DOS commands
- The method for win10 system to enter the control panel is as follows:
- 【Rust笔记】05-错误处理
- How to use Jupiter notebook
- Deeply understand the underlying data structure of MySQL index
- Gaussian elimination acwing 883 Gauss elimination for solving linear equations
- URL backup 1
- Character pyramid
猜你喜欢
LeetCode 535. TinyURL 的加密与解密
Monotonic stack -503 Next bigger Element II
22-06-28 Xi'an redis (02) persistence mechanism, entry, transaction control, master-slave replication mechanism
I made mistakes that junior programmers all over the world would make, and I also made mistakes that I shouldn't have made
Dom4j遍历和更新XML
Life cycle of Servlet
ES6 promise learning notes
第一个Servlet
[RPC] RPC remote procedure call
Deep parsing JVM memory model
随机推荐
22-05-26 Xi'an interview question (01) preparation
PHP function date (), y-m-d h:i:s in English case
Escape from heaven and forget what he suffered. In ancient times, it was called the punishment of escape from heaven. Article collection
How to deal with the core task delay caused by insufficient data warehouse resources
Concurrent programming (V) detailed explanation of atomic and unsafe magic classes
我們有個共同的名字,XX工
ES6 promise learning notes
[concurrent programming] atomic operation CAS
MySQL three logs
Use of sort command in shell
单调栈-42. 接雨水
The difference between if -n and -z in shell
cres
LeetCode 241. 为运算表达式设计优先级
树形DP AcWing 285. 没有上司的舞会
Alibaba canaladmin deployment and canal cluster Ha Construction
[concurrent programming] collaboration between threads
【Rust笔记】06-包和模块
[rust notes] 09- special types and generics
JS ternary operator - learning notes (with cases)