Leetcode 124. Binary Tree Maximum Path Sum

本题的思路其实和 Longest Univalue Path 这题的内容是一致的, 如果最长相同数值路径的逻辑能明白, 这里就是把数值相等的判断, 换成了数值加和的判断 

递归思路

二叉树的路径问题常用递归来解决, 这里递归函数求的是以当前结点为起始的链路的最大值, 这里可能存在三种情况 :

  1. 以当前结点为起始的左子树链路为最大值
  2. 以当前结点为起始的右子树链路为最大值
  3. 不包含左右子树, 当前结点就是最大值

而我们要求的最大路径和 res 对应的链路是可以左子树 + 当前结点 + 右子树的情况的, 所以我们在这个过程中, 还要对我们的 res 进行数值上的更新. 

class Solution {
    private int res;
    public int maxPathSum(TreeNode root) {
        // set the initial value 
        res = Integer.MIN_VALUE;
        PathSum(root);
        return res;
    }
    public int PathSum(TreeNode node) {
        if (node == null)
            return 0;
        // the max path sum start with the left child tree
        int left = PathSum(node.left);
        // the max path sum start with the right child tree
        int right = PathSum(node.right);
        if (left >= 0) {
            res = Math.max(res, right >= 0 ? left + right + node.val : left + node.val);
        } else {
            res = Math.max(res, right >= 0 ? right + node.val : node.val);
        }
        // we have to return the max path sum start with current node
        
        if (left >= 0)
            return right >= 0 ? Math.max(left, right)  + node.val : left + node.val;
        else 
            return right >= 0 ? right + node.val : node.val;
    }
}

上面的代码是我自己完成的, 但是很明显这里的数值运算加上了太多的判断, 这里可以进行优化, 当 left 或者 right 的数值小于 0 的情况下, 我们是肯定不会加上该数值的, 所以可以直接将该数值变为 0, 后面的运算就可以都加上来.

class Solution {
    private int res;
    public int maxPathSum(TreeNode root) {
        // set the initial value 
        res = Integer.MIN_VALUE;
        PathSum(root);
        return res;
    }
    public int PathSum(TreeNode node) {
        if (node == null)
            return 0;
        // the max path sum start with the left child tree
        int left = PathSum(node.left);
        // the max path sum start with the right child tree
        int right = PathSum(node.right);
        if (left < 0) left = 0;
        if (right < 0) right = 0;
        res = Math.max(left + right + node.val, res);
        // we have to return the max path sum start with current node
        return Math.max(left, right) + node.val;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值