515. 在每个树行中找最大值
您需要在二叉树的每一行中找到最大的值。
示例:
输入:
1
/
3 2
/
5 3 9
输出: [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> list = new ArrayList<>();
public List<Integer> largestValues(TreeNode root) {
dfs(root,0);
return list;
}
public void dfs(TreeNode tree,int cen){
if(tree==null) return;
if(cen==list.size()) list.add(tree.val);
else{
if(list.get(cen)<tree.val){
list.remove(cen);
list.add(cen,tree.val);
}
}
dfs(tree.left,cen+1);
dfs(tree.right,cen+1);
}
}