码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Maximum Path Sum 解题注意

时间:2014-12-24 07:35:49      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

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;
     
    }

 

Binary Tree Maximum Path Sum 解题注意

标签:

原文地址:http://www.cnblogs.com/oceancloud/p/4181531.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!