
https://leetcode.com/problems/find-largest-value-in-each-tree-row
515. Find Largest Value in Each Tree Row
給你一個二元樹,找出每一個 level 最大的元素列表。
Example 1:
https://assets.leetcode.com/uploads/2020/08/21/largest_e1.jpg
Input: root = [1,3,2,5,3,null,9]
Output: [1,3,9]
Example 2:
Input: root = [1,2,3]
Output: [1,3]
思路:
1.普通 BFS 遍歷,並記錄每一層最大的元素加入列表即可。
Java Code:
----------------------------------------------------------
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
int max = Integer.MIN_VALUE;
for (int i = 0; i < size; i++) {
TreeNode curr = queue.poll();
max = Math.max(max, curr.val);
if (curr.left != null) {
queue.offer(curr.left);
}
if (curr.right != null) {
queue.offer(curr.right);
}
}
res.add(max);
}
return res;
}
}
----------------------------------------------------------
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.73.13 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1698130960.A.D66.html
※ 編輯: Rushia (122.100.73.13 臺灣), 10/24/2023 15:03:35
