当前位置:网站首页>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;
}
}边栏推荐
- Analysis of Alibaba canal principle
- JS non Boolean operation - learning notes
- Shell script kills the process according to the port number
- Es8 async and await learning notes
- Deeply understand the underlying data structure of MySQL index
- TP5 multi condition sorting
- Format - C language project sub file
- Log4j2 vulnerability recurrence and analysis
- How to use Jupiter notebook
- Using variables in sed command
猜你喜欢

TP5 multi condition sorting

Facial expression recognition based on pytorch convolution -- graduation project

How to use Jupiter notebook

Slice and index of array with data type

Wonderful review | i/o extended 2022 activity dry goods sharing

Final review of Database Principles

XPath实现XML文档的查询

Find the combination number acwing 885 Find the combination number I

ES6 promise learning notes

Gaussian elimination acwing 883 Gauss elimination for solving linear equations
随机推荐
Debug debugging - Visual Studio 2022
数位统计DP AcWing 338. 计数问题
Binary tree sorting (C language, int type)
Using variables in sed command
低代码前景可期,JNPF灵活易用,用智能定义新型办公模式
Gaussian elimination acwing 883 Gauss elimination for solving linear equations
Slice and index of array with data type
Query XML documents with XPath
Deep parsing JVM memory model
Convert video to GIF
[rust notes] 07 structure
JS ternary operator - learning notes (with cases)
Parameters of convolutional neural network
Introduction to the usage of getopts in shell
[rust note] 10 operator overloading
On the difference and connection between find and select in TP5 framework
Format - C language project sub file
樹形DP AcWing 285. 沒有上司的舞會
20220630学习打卡
Binary to decimal, decimal to binary