当前位置:网站首页>LeetCode 515. Find the maximum value in each tree row
LeetCode 515. Find the maximum value in each tree row
2022-07-03 09:02:00 【Sasakihaise_】
515. Find the maximum in each tree row

【BFS Level traversal 】
class Solution {
// Level traversal 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】 Use a parameter to record layer information
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;
}
}
边栏推荐
- Deep parsing (picture and text) JVM garbage collector (II)
- 浅谈企业信息化建设
- LeetCode 513. 找树左下角的值
- First Servlet
- Annotations simplify configuration and loading at startup
- MySQL index types B-tree and hash
- 22-06-28 Xi'an redis (02) persistence mechanism, entry, transaction control, master-slave replication mechanism
- Binary tree sorting (C language, char type)
- How to use Jupiter notebook
- excel一小时不如JNPF表单3分钟,这样做报表,领导都得点赞!
猜你喜欢

DOM render mount patch responsive system

Deep parsing (picture and text) JVM garbage collector (II)

Try to reprint an article about CSDN reprint

教育信息化步入2.0,看看JNPF如何帮助教师减负,提高效率?

20220630学习打卡

拯救剧荒,程序员最爱看的高分美剧TOP10

即时通讯IM,是时代进步的逆流?看看JNPF怎么说

我們有個共同的名字,XX工

Alibaba canaladmin deployment and canal cluster Ha Construction

Tree DP acwing 285 A dance without a boss
随机推荐
请求参数的发送和接收
URL backup 1
dried food! What problems will the intelligent management of retail industry encounter? It is enough to understand this article
MySQL three logs
LeetCode 532. K-diff number pairs in array
20220630学习打卡
Monotonic stack -42 Connect rainwater
What is the difference between sudo apt install and sudo apt -get install?
ES6 promise learning notes
Use of sort command in shell
Binary tree sorting (C language, char type)
JS non Boolean operation - learning notes
LeetCode 535. TinyURL 的加密与解密
[concurrent programming] collaboration between threads
[rust notes] 11 practical features
LeetCode 438. 找到字符串中所有字母异位词
状态压缩DP AcWing 291. 蒙德里安的梦想
樹形DP AcWing 285. 沒有上司的舞會
Try to reprint an article about CSDN reprint
网络安全必会的基础知识