LeetCode--关于在每个树行中找最大值
题目描述
如题
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private List<Integer> list = new ArrayList<>();
public List<Integer> largestValues(TreeNode root) {
preOrder(root, 0);
return list;
}
private void preOrder(TreeNode root, int level)
{
if(root == null)
{
return;
}
if(list.size() == level)
{
list.add(root.val);
}
else if(root.val > list.get(level))
{
list.set(level, root.val);
}
preOrder(root.left, level + 1);
preOrder(root.right, level + 1);
}
}