LeetCode - Binary Tree Maximum Path Sum

https://leetcode.com/problems/binary-tree-maximum-path-sum/

这道题可以用递归做,首先,应该有一个全局变量来保存当前遇到的最大path值。

对于每个节点而言,经过它的最大path值,应该是左边的最大path加右边的最大path加自己,如果左边或者右边的最大path是负数,那么就不加这一部分。

另外,对于这个节点的父节点而言,经过父节点的path不可能同时经过这个节点的左右子树,只能经过这个节点的左子树或者右子树,因此这个节点返回给它的父节点的,应该是它单边的最大path

public class Solution {
    public int maxPathSum(TreeNode root) {
        int[] max = new int[1];
        max[0] = root.val;
        getMax(root, max);
        return max[0];
    }
    public int getMax(TreeNode root, int[] max){
        if(root==null) return 0;
        int left = getMax(root.left, max);
        int right = getMax(root.right, max);
        if(left<0) left=0;
        if(right<0) right = 0;
        int localMax = root.val+left+right;
        if(localMax>max[0]) max[0] = localMax;
        return Math.max(root.val+left, root.val+right);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值