LeetCode 515. 在每个树行中找最大值(Find Largest Value in Each Tree Row)

515. 在每个树行中找最大值
515. Find Largest Value in Each Tree Row

题目描述
You need to find the largest value in each row of a binary tree.

您需要在二叉树的每一行中找到最大的值。

LeetCode515. Find Largest Value in Each Tree Row

Example:

Input:
          1
         / \
        3   2
       / \   \  
      5   3   9 

Output: [1, 3, 9]

Java 实现
TreeNode Class

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}
import java.util.LinkedList;
import java.util.List;

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new LinkedList<>();
        helper(root, res, 0);
        return res;
    }

    public void helper(TreeNode root, List<Integer> res, int depth) {
        if (root == null) {
            return;
        }
        if (depth == res.size()) {
            res.add(root.val);
        } else {
            res.set(depth, Math.max(res.get(depth), root.val));
        }
        helper(root.left, res, depth + 1);
        helper(root.right, res, depth + 1);
    }
}

参考资料

转载于:https://www.cnblogs.com/hglibin/p/10891088.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值