1、用队列进行处理。分别找到每一行中的最大值。
public List<Integer> largestValues(TreeNode root) {
List<Integer> result = new ArrayList<>();
if(root == null) {return result;}
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 curr = queue.poll();
max = Math.max(max, curr.val);
if(curr.left != null) queue.offer(curr.left);
if(curr.right != null) queue.offer(curr.right);
}
result.add(max);
}
return result;
}
2、递归解法
List<Integer> result = new ArrayList<>();
public List<Integer> largestValues(TreeNode root) {
// if(root != null) result.add(root.val);
helper(root,0);
return result;
}
public void helper(TreeNode root, int dep) {
if(root == null) return;
if(dep == result.size()) {
result.add(root.val);
}else {
result.set(dep, Math.max(root.val,result.get(dep)));
}
helper(root.left,dep+1);
helper(root.right,dep+1);
}