当前位置:网站首页>[LeetCode]515. Find the maximum value in each tree row
[LeetCode]515. Find the maximum value in each tree row
2022-06-27 21:50:00 【A Fei algorithm】
subject
515. Find the maximum in each tree row
Given the root node of a binary tree root , Please find the maximum value of each layer in the binary tree .
Example 1:
Input : root = [1,3,2,5,3,null,9]
Output : [1,3,9]
Example 2:
Input : root = [1,2,3]
Output : [1,3]
Tips :
The range of the number of nodes in a binary tree is [0,104]
-231 <= Node.val <= 231 - 1
Method 1: Sequence traversal
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
if (root != null) q.offer(root);
while (!q.isEmpty()) {
int size = q.size();
int t = Integer.MIN_VALUE;
for (int i = 0; i < size; i++) {
TreeNode cur = q.poll();
t = Math.max(t, cur.val);
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
}
res.add(t);
}
return res;
}
Method 2:DFS
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
dfs(root, 0, res);
return res;
}
//depth Table the depth of the currently processed node
private void dfs(TreeNode root, int depth, List<Integer> res) {
if (depth == res.size()) {
// The node that first came to this depth
res.add(root.val);
} else {
// Not the first time to this floor
res.set(depth, Math.max(root.val, res.get(depth)));
}
if (root.left != null) dfs(root.left, depth + 1, res);
if (root.right != null) dfs(root.right, depth + 1, res);
}
边栏推荐
- [LeetCode]动态规划解分割数组II[Arctic Fox]
- PCIE知识点-008:PCIE switch的结构
- Go from introduction to actual combat -- channel closing and broadcasting (notes)
- Go从入门到实战——仅执行一次(笔记)
- Codeforces Global Round 14
- Xiao Wang's interview training task
- ICML2022 | 可扩展深度高斯马尔可夫随机场
- Quick excel export
- 空指针异常
- "Apprendre cette image" apparaît sur le Bureau win11 comment supprimer
猜你喜欢
随机推荐
抖音的兴趣电商已经碰到流量天花板?
SQL必需掌握的100个重要知识点:使用函数处理数据
让马化腾失望了!Web3.0,毫无希望
Go from starting to Real - Interface (note)
C语言程序设计详细版 (学习笔记1) 看完不懂,我也没办法。
快速excel导出
Slow bear market, bit Store provides stable stacking products to help you cross the bull and bear
CEPH distributed storage
100 important knowledge points that SQL must master: combining where clauses
100 important knowledge points for SQL: in operator
Go从入门到实战——错误机制(笔记)
Method of reading file contents by Excel
TreeSet details
Contest 2050 and Codeforces Round #718 (Div. 1 + Div. 2)
Scrum和看板的区别
流程控制任务
强制 20 天内开发 APP 后集体被裁,技术负责人怒批:祝“早日倒闭!”
Day8 ---- 云资讯项目介绍与创建
win11桌面出現“了解此圖片”如何删除
excel读取文件内容方法









