BiruLyu
7/3/2017 - 5:50 PM

515. Find Largest Value in Each Tree Row(BFS).java

``````/**
* 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> result = new ArrayList();
if(root==null){
return result;
}
if(root.left!=null) helper(root.left, result, 1);
if(root.right!=null) helper(root.right, result, 1);
return result;
}

void helper(TreeNode root, List<Integer> result, int level){
if(result.size()==level){
}else if(root.val > result.get(level)){
result.set(level, root.val);
}
if(root.left!=null) helper(root.left, result, level+1);
if(root.right!=null) helper(root.right, result, level+1);
}
}``````
``````/**
* 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> res = new ArrayList<>();
if (root == null) return res;
queue.offer(root);
while(!queue.isEmpty()) {
int curSize = queue.size();
int max = Integer.MIN_VALUE;
for (int i = 0; i < curSize; i++) {
TreeNode cur = queue.poll();
max = Math.max(max, cur.val);
if (cur.left != null) queue.offer(cur.left);
if (cur.right != null) queue.offer(cur.right);
}