当前位置:网站首页>LeetCode 515. 在每个树行中找最大值
LeetCode 515. 在每个树行中找最大值
2022-07-03 08:49:00 【Sasakihaise_】

【BFS 层次遍历】
class Solution {
// 层次遍历 9:15 9:22
List<Integer> ans = new ArrayList();
public void bfs(TreeNode node){
if(node == null) return;
Queue<TreeNode> queue = new LinkedList();
queue.offer(node);
while(!queue.isEmpty()){
int k = queue.size();
int max = Integer.MIN_VALUE;
while(k-- > 0){
TreeNode top = queue.poll();
max = Math.max(max, top.val);
if(top.left != null) queue.offer(top.left);
if(top.right != null) queue.offer(top.right);
}
ans.add(max);
}
}
public List<Integer> largestValues(TreeNode root) {
bfs(root);
return ans;
}
}【DFS】用一个参数来记录层信息
class Solution {
// DFS 9:38
List<Integer> ans = new ArrayList();
public void dfs(TreeNode node, int t){
if(node == null) return;
if(ans.size() == t) ans.add(node.val);
else ans.set(t, Math.max(ans.get(t), node.val));
dfs(node.left, t + 1);
dfs(node.right, t + 1);
}
public List<Integer> largestValues(TreeNode root) {
dfs(root, 0);
return ans;
}
}
边栏推荐
- [redis] redis persistent RDB vs AOF (source code)
- 状态压缩DP AcWing 291. 蒙德里安的梦想
- 22-06-28 西安 redis(02) 持久化机制、入门使用、事务控制、主从复制机制
- Analysis of Alibaba canal principle
- 20220630 learning clock in
- Tree DP acwing 285 A dance without a boss
- 请求参数的发送和接收
- TP5 multi condition sorting
- [rust notes] 07 structure
- Annotations simplify configuration and loading at startup
猜你喜欢

Allocation exception Servlet

Life cycle of Servlet

LeetCode 75. 颜色分类

SQL statement error of common bug caused by Excel cell content that is not paid attention to for a long time

Annotations simplify configuration and loading at startup

On the setting of global variable position in C language

Mortgage Calculator

Sending and receiving of request parameters

Redux - learning notes

Analysis of Alibaba canal principle
随机推荐
Try to reprint an article about CSDN reprint
[rust notes] 12 closure
Slice and index of array with data type
[rust notes] 13 iterator (Part 1)
LeetCode 324. 摆动排序 II
状态压缩DP AcWing 91. 最短Hamilton路径
【Rust笔记】02-所有权
php public private protected
Complex character + number pyramid
20220630 learning clock in
Mortgage Calculator
Apache startup failed phpstudy Apache startup failed
22-06-28 Xi'an redis (02) persistence mechanism, entry, transaction control, master-slave replication mechanism
22-06-27 Xian redis (01) commands for installing five common data types: redis and redis
Convert video to GIF
[rust notes] 08 enumeration and mode
PHP mnemonic code full text 400 words to extract the first letter of each Chinese character
Drawing maze EasyX library with recursive backtracking method
LeetCode 535. TinyURL 的加密与解密
Eating fruit