515. Find Largest Value in Each Tree Row
1、原题
You need to find the largest value in each row of a binary tree.
Example:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
2、题意与思路
这道题的意思很简单,就是寻找一个二叉树中每一层中最大的值。
这道题的思路也是很简单,就是一个简单的广搜问题。但是这里有点不同的是,我们要找到同一层中的数值。一开始我的想法是还要用一个新的队列来记录每一个元素的层数。但是这样做后,感觉效果很不好。后来想到了我们可以直接根据我们队列的size大小来记录每一层的宽度,这样就简单了很多。
3、代码
public List<Integer> largestValues(TreeNode root) {
//记录每一层的最大值
List<Integer> list = new ArrayList<Integer>();
//用于广搜记录
List<TreeNode> queue = new ArrayList<TreeNode>();
int queueSize = root == null ? 0 : 1;
queue.add(root);
while (queueSize > 0) {
int maxValue = Integer.MIN_VALUE;
//收搜每一层
for (int i = 0; i < queueSize; i++) {
TreeNode item = queue.remove(0);
maxValue = maxValue > item.val ? maxValue : item.val;
if (item.left != null) queue.add(item.left);
if (item.right != null) queue.add(item.right);
}
list.add(maxValue);
//获取下一层的size
queueSize = queue.size();
}
return list;
}