515. Find Largest Value in Each Tree Row
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]
解法
层次遍历,每一层入队列,再根据该层的长度分别出队列,再添加出队列的元素对应的左右孩子。直到队列的长度为0。在每一层的操作中,计算最大的元素添加到list中。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> ret = new ArrayList<Integer>();
if (root == null) {
return ret;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (!queue.isEmpty()) {
int max = Integer.MIN_VALUE;
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode head = queue.poll();
if (head.val > max) {
max = head.val;
}
if (head.left != null) {
queue.offer(head.left);
}
if (head.right != null) {
queue.offer(head.right);
}
}
ret.add(max);
}
return ret;
}
}