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]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
helper(root, res, 0);
return res;
}
private void helper(TreeNode root, List<Integer> res, int d){
if(root == null){
return;
}
if(d == res.size()){
res.add(root.val);
}else{
res.set(d, Math.max(res.get(d), root.val));
}
helper(root.left, res, d + 1);
helper(root.right, res, d + 1);
}
}