/**
* 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;
}
result.add(root.val);
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){
result.add(root.val);
}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<TreeNode> queue = new LinkedList<>();
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);
}
res.add(max);
}
return res;
}
}