Topic22——124. 二叉树中的最大路径和

题目路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。

路径和 是路径中各节点值的总和。

给你一个二叉树的根节点 root ,返回其 最大路径和

示例 1

在这里插入图片描述

输入:root = [1,2,3]
输出:6
解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6

示例 2

在这里插入图片描述

输入:root = [-10,9,20,null,null,15,7]
输出:42
解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42

提示:

树中节点数目范围是 [1, 3 * 104]
-1000 <= Node.val <= 1000

class Solution {
    public int maxPathSum(TreeNode root) {
        int node_val = tryMaxPath(root);
        return max;
    }

    public Map<TreeNode, Integer> map = new HashMap<>();  //map用来存(当前节点,当前节点值 + max(左路径,右路径))
    public int max = Integer.MIN_VALUE;   //用来存储最大路径和

    public int tryMaxPath(TreeNode root) {
        if(root == null)
            return 0;
        if(map.containsKey(root))
            return map.get(root);
        int value = Math.max(tryMaxPath(root.left), tryMaxPath(root.right));   //取左右子树较大的
        if(value < 0)
            value = 0;
        map.put(root, root.val + value);
        max = Math.max(max, root.val + (root.left != null && map.get(root.left) > 0 ? map.get(root.left) : 0) 
                                    + (root.right != null && map.get(root.right) > 0 ? map.get(root.right) : 0));   //当前节点值 + 左值(>0) + 右值(>0)
        return map.get(root);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值