当前位置:网站首页>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;
}
}
边栏推荐
- Binary tree sorting (C language, char type)
- Unity Editor Extension - drag and drop
- 注解简化配置与启动时加载
- [RPC] RPC remote procedure call
- How to use Jupiter notebook
- SQL statement error of common bug caused by Excel cell content that is not paid attention to for a long time
- PHP mnemonic code full text 400 words to extract the first letter of each Chinese character
- TP5 multi condition sorting
- Parameters of convolutional neural network
- PHP uses foreach to get a value in a two-dimensional associative array (with instances)
猜你喜欢
随机推荐
[concurrent programming] collaboration between threads
TP5 multi condition sorting
20220630 learning clock in
LinkedList set
Arbre DP acwing 285. Un bal sans patron.
First Servlet
How to deal with the core task delay caused by insufficient data warehouse resources
树形DP AcWing 285. 没有上司的舞会
[MySQL] MySQL Performance Optimization Practice: introduction of database lock and index search principle
Life cycle of Servlet
producer consumer problem
Complex character + number pyramid
【Rust 笔记】10-操作符重载
22-06-27 Xian redis (01) commands for installing five common data types: redis and redis
Location of package cache downloaded by unity packagemanager
JS non Boolean operation - learning notes
Concurrent programming (VI) ABA problems and solutions under CAS
20220630学习打卡
DOM 渲染系统(render mount patch)响应式系统
SQL statement error of common bug caused by Excel cell content that is not paid attention to for a long time









