【LeetCode】Binary Tree Maximum Path Sum

参考链接


http://blog.youkuaiyun.com/aay_dps/article/details/8186372

题目描述

Binary Tree Maximum Path Sum

 

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1
      / \
     2   3

Return 6.


题目分析

找出一条路径和最大的值。


定义F(root) 是i的孩子到i这段路中的最大值。那么F(root) = MAX(root->val,F(root->left),F(root->right))

而过当前结点的最大路径各就是root->val + F(root->left)>0?F(root->left):0+ F(root->right)>0?F(root->right):0

遍历所有结点,就可以求出最大路径和了。



总结

在使用INT_MIN时,不要加一个负数,或减一个正数,否则会溢出。



代码示例

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxPathSumUtil(TreeNode* root, int& maxLocal)
    {
        if(root == NULL) return INT_MIN;
        int left = maxPathSumUtil(root->left, maxLocal);
        int right = maxPathSumUtil(root->right, maxLocal);
        int local = root->val;
        if(left > 0) local += left;
        if(right > 0) local += right;
        maxLocal = max(local, maxLocal);
        return max(max(left, right), 0)+root->val;
    }
    int maxPathSum(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(root == NULL) return 0;
        int maxLocal = root->val;
        maxPathSumUtil(root, maxLocal);
        return maxLocal;
    }
};

class Solution {
public:
    int maxPathSum(TreeNode *root) {
        int maxSum = INT_MIN;
        maxPathSumHelper(root,maxSum);
        return maxSum;
    }
    int maxPathSumHelper(TreeNode *root, int &maxSum)
    {
        if(root == NULL)    return INT_MIN;////////////////////后面不能再加负数
        int left = maxPathSumHelper(root->left,maxSum);
        int right = maxPathSumHelper(root->right,maxSum);
        int tmpmax = root->val;
        if(left>0) tmpmax+=left;
        if(right>0) tmpmax+=right;
        
        maxSum = max(maxSum,tmpmax);
        
        //return max(root->val,max(root->val+left,root->val+right));
        return root->val+max(max(left,right),0);
    }
};





推荐学习C++的资料

C++标准函数库
在线C++API查询

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值