当前位置:网站首页>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;
}
}
边栏推荐
- too many open files解决方案
- Wonderful review | i/o extended 2022 activity dry goods sharing
- 低代码起势,这款信息管理系统开发神器,你值得拥有!
- Baidu editor ueeditor changes style
- AcWing 785. 快速排序(模板)
- 剑指 Offer II 029. 排序的循环链表
- C language file reading and writing
- I made mistakes that junior programmers all over the world would make, and I also made mistakes that I shouldn't have made
- Parameters of convolutional neural network
- What is the difference between sudo apt install and sudo apt -get install?
猜你喜欢
Try to reprint an article about CSDN reprint
Concurrent programming (III) detailed explanation of synchronized keyword
Slice and index of array with data type
Binary tree sorting (C language, char type)
Query XML documents with XPath
常见渗透测试靶场
Servlet的生命周期
我们有个共同的名字,XX工
樹形DP AcWing 285. 沒有上司的舞會
Vscode connect to remote server
随机推荐
Notes and bugs generated during the use of h:i:s and y-m-d
cres
Common penetration test range
[rust notes] 07 structure
[rust notes] 13 iterator (Part 1)
LeetCode 871. 最低加油次数
AcWing 788. 逆序对的数量
LeetCode 715. Range 模块
Six dimensional space (C language)
我们有个共同的名字,XX工
教育信息化步入2.0,看看JNPF如何帮助教师减负,提高效率?
AcWing 787. 归并排序(模板)
分配异常的servlet
PHP uses foreach to get a value in a two-dimensional associative array (with instances)
Try to reprint an article about CSDN reprint
LeetCode 30. 串联所有单词的子串
求组合数 AcWing 886. 求组合数 II
22-05-26 西安 面试题(01)准备
数字化管理中台+低代码,JNPF开启企业数字化转型的新引擎
Low code momentum, this information management system development artifact, you deserve it!