Crack LeetCode 之 124. Binary Tree Maximum Path Sum

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

本题的难点在于每条路径可以由树中的任意两个节点相连组成,解题方法还是递归。需要注意的是递归函数的返回值不是子树的和,而是包含根节点的左子树、根节点或者包含根节点的右子树,这也是本题的递归函数和其他题目不同的地方。本题的时间复杂度是O(n),空间复杂度也是O(n)。以下是C++代码和python代码。
 

class Solution {
public:
	int maxPathSum(TreeNode * root) {
		if (root == NULL)
			return 0;

		int res = root->val;
		helper(root, res);
		return res;
	}

	int helper(TreeNode * root, int & res)
	{
		if (root == NULL)
			return 0;

		int left = helper(root->left, res);
		int right = helper(root->right, res);
		int cur = root->val + (left>0 ? left : 0) + (right>0 ? right : 0);
		if (cur>res)
			res = cur;
		return root->val + max(left, max(right, 0));
	}
};
class Solution:
    maxVal = 0

    def maxPathSum(self, root):
        if root == None:
            return 0

        maxVal = root.val
        self.helper(root)
        return maxVal

    def helper(self):
        if root == None:
            return 0

        left = helper(root.left);
        right = helper(root.right);
        cur = root.val + max(left, 0) + max(right, 0)

        if cur > maxVal:
            maxVal = cur

        return root.val + max(left, max(right,0))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值