【Binary Tree Maximum Path Sum】cpp

题目:

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.

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
        int maxPathSum(TreeNode* root)
        {
            int max_sum = INT_MIN;
            Solution::dfs4MaxSum(root, max_sum);
            return max_sum;
        }
        static int dfs4MaxSum(TreeNode* root, int& max_sum)
        {
            int ret=0;
            if ( !root ) return ret;
            int l = Solution::dfs4MaxSum(root->left, max_sum);
            int r = Solution::dfs4MaxSum(root->right, max_sum);
            if ( l>0 ) ret += l;
            if ( r>0 ) ret += r;
            ret += root->val;
            max_sum = std::max(ret, max_sum);
            return std::max(root->val, std::max(root->val+l, root->val+r));
        }
};

tips:

求array最大子序列和是一样的思路。只不过binary tree不是一路,而是分左右两路,自底向上算。

主要注意的地方如下:

1. 维护一个全局最优变量(max_sum),再用ret存放包括前节点在内的局部最大值;每次比较max_sum和ret时,max_sum代表的是不包含当前节点在内的全局最优,ret代表的是一定包含当前节点在内的全局最优。

2. dfs4MaxSum返回时需要注意,left和right只能算一路,不能一起都返到上一层。因为题目中要求的path抻直了只能是一条线,不能带分叉的。

==============================================

第二次过这道题,大体思路有了,细节的错误也都犯了,改过来强化一次AC了。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
        int maxPathSum(TreeNode* root)
        {
            int ret = INT_MIN;
            if (root) Solution::maxPS(root, ret);
            return ret;
        }
        static int maxPS( TreeNode* root, int& maxSum)
        {
            if ( !root ) return 0;
            int l = Solution::maxPS(root->left, maxSum);
            int r = Solution::maxPS(root->right, maxSum);
            maxSum = max(maxSum, root->val+(l>0?l:0)+(r>0?r:0));
            return max(root->val,root->val+max(r,l));
        }
};
原文地址:https://www.cnblogs.com/xbf9xbf/p/4511277.html