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.

 

解题思路,递归

   a

b      c

curmax = max (a+b, a, a+c) //计算当前节点单边最大值,

如果a+b 最大,那就是说,把左子树包含进来,有利可图

如果a+c 最大,把右子树包含进来,有利可图

如果 a,最大,那就到a为止,最好了。

gmax = max(gmax, max(curmax, a+b+c)) 

这个是看要不要抛弃前面的结果.

 

void maxpathsumhelper(TreeNode* root, int& currentsum, int& maxsum)
    {
        if(root == NULL)return;
        int leftsum  = 0;
        int rightsum = 0;
        
        maxpathsumhelper(root->left,leftsum, maxsum);
        maxpathsumhelper(root->right,rightsum, maxsum);
        currentsum = max(root->val, max(root->val + leftsum, root->val + rightsum)); //this value will passedback
        maxsum = max(maxsum, max(currentsum, leftsum + rightsum + root->val));
    }
    
    int maxPathSum(TreeNode *root) {
     
     if(root == NULL) return 0;
     int csum = INT_MIN;
     int maxsum = INT_MIN;
     
     maxpathsumhelper(root, csum, maxsum);
     return maxsum;
     
    }

 

posted @ 2014-12-24 07:19  来自海边的一片云  阅读(149)  评论(0编辑  收藏  举报