当前位置:网站首页>[LeetCode]508. 出現次數最多的子樹元素和
[LeetCode]508. 出現次數最多的子樹元素和
2022-06-27 21:49:00 【阿飛算法】
題目
508. 出現次數最多的子樹元素和
給你一個二叉樹的根結點 root ,請返回出現次數最多的子樹元素和。如果有多個元素出現的次數相同,返回所有出現次數最多的子樹元素和(不限順序)。
一個結點的 「子樹元素和」 定義為以該結點為根的二叉樹上所有結點的元素之和(包括結點本身)。
示例 1:
輸入: root = [5,2,-3]
輸出: [2,-3,4]
示例 2:
輸入: root = [5,2,-5]
輸出: [2]
提示:
節點數在 [1, 104] 範圍內
-105 <= Node.val <= 105
方法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;//出現的最大的次數
//記錄當前出現的sum 的次數
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从入门到实战——package(笔记)

Go from entry to practice - dependency management (notes)

Go从入门到实战——错误机制(笔记)

语言弱点列表--CWE,一个值得学习的网站

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

Tiktok's interest in e-commerce has hit the traffic ceiling?

Process control task

洛谷P5706 再分肥宅水

JVM memory structure when creating objects

win11桌面出現“了解此圖片”如何删除
随机推荐
Go from entry to practice - dependency management (notes)
100 important knowledge points that SQL must master: retrieving data
DO280OpenShift访问控制--security policy和章节实验
Oracle migration MySQL unique index case insensitive don't be afraid
Go从入门到实战——Context与任务取消(笔记)
GBase 8a的create database 会被查询耗时很长怀疑卡住的现象分析
Bit. Store: long bear market, stable stacking products may become the main theme
CORBA 架构体系指南(通用对象请求代理体系架构)
Acwing周赛57-最长连续子序列-(二分or树状数组)
Null pointer exception
oracle迁移mysql唯一索引大小写不区分别怕
Installing Oracle11g under Linux
Flask----应用案例
Go from entry to practice -- CSP concurrency mechanism (note)
∫(0→1) ln(1+x) / (x ² + 1) dx
100 important knowledge points that SQL must master: using functions to process data
Go从入门到实战——行为的定义和实现(笔记)
ABC-Teleporter Setting-(思维+最短路)
Go从入门到实战—— 多路选择和超时控制(笔记)
Go从入门到实战——接口(笔记)