Skip to content

Commit 4bcd1ca

Browse files
committed
solve 515.在每个树行中找最大值
1 parent cd094e7 commit 4bcd1ca

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*
2+
* @lc app=leetcode.cn id=515 lang=java
3+
*
4+
* [515] 在每个树行中找最大值
5+
*
6+
* https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/description/
7+
*
8+
* algorithms
9+
* Medium (60.38%)
10+
* Likes: 63
11+
* Dislikes: 0
12+
* Total Accepted: 11.5K
13+
* Total Submissions: 19.1K
14+
* Testcase Example: '[1,3,2,5,3,null,9]'
15+
*
16+
* 您需要在二叉树的每一行中找到最大的值。
17+
*
18+
* 示例:
19+
*
20+
*
21+
* 输入:
22+
*
23+
* ⁠ 1
24+
* ⁠ / \
25+
* ⁠ 3 2
26+
* ⁠ / \ \
27+
* ⁠ 5 3 9
28+
*
29+
* 输出: [1, 3, 9]
30+
*
31+
*
32+
*/
33+
34+
// @lc code=start
35+
/**
36+
* Definition for a binary tree node.
37+
* public class TreeNode {
38+
* int val;
39+
* TreeNode left;
40+
* TreeNode right;
41+
* TreeNode(int x) { val = x; }
42+
* }
43+
*/
44+
class Solution {
45+
public List<Integer> largestValues(TreeNode root) {
46+
List<Integer> result = new ArrayList<>();
47+
if (root == null) {
48+
return result;
49+
}
50+
51+
Queue<TreeNode> queue = new LinkedList<>();
52+
queue.offer(root);
53+
54+
while (!queue.isEmpty()) {
55+
int size = queue.size();
56+
int max = Integer.MIN_VALUE;
57+
for (int i = 0; i < size; i++) {
58+
TreeNode node = queue.poll();
59+
if (node.val > max) {
60+
max = node.val;
61+
}
62+
if (node.left != null) {
63+
queue.offer(node.left);
64+
}
65+
if (node.right != null) {
66+
queue.offer(node.right);
67+
}
68+
}
69+
result.add(max);
70+
}
71+
72+
return result;
73+
}
74+
}
75+
// @lc code=end
76+

0 commit comments

Comments
 (0)