You need to find the largest value in each row of a binary tree.Have you met this question in a real interview? YesProblem Correction
Example
Input: [1,3,2,5,3,#,9]
Output: [1, 3, 9]
和层序遍历的题基本一样,只是加上个找最大值
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: a root of integer
* @return: return a list of integer
*/
public List<Integer> largestValues(TreeNode root) {
// write your code here
List<Integer> list = new ArrayList<>();
if(root == null)
return list;
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 node = queue.poll();
if(node.left != null){
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
max = Math.max(max,node.val);
}
list.add(max);
}
return list;
}
}