题目:
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
.
将数中的路径的最大值设为一个全局变量maxresult;
首先,对树中的每个节点,计算出以该节点为根的路径的最大值;
最大值计算如下:
max(左子树的最大值,右子树的最大值,0)
加入0 的原因是,左右子树可能最大值为负数,那么此时,就以该节点为经过该点的最大值
其次,更新maxresult;
更新规则如下:
int tmp = root->val;
如果:左子树的最大路径的和 >0, 则tmp = root->val+left
如果:右子树的最大路径的和>0, 则tmp = tmp + right;
此时,tmp表示经过root点的最大路径的值,
如果tmp > maxresult, 则更新maxresult
/**
* 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 maxPath(TreeNode *root, int& maxresult)
{
if(!root)
return 0;
if(!root->left && !root->right)
{
if(root->val > maxresult)
maxresult = root->val;
return root->val;
}
int tmpleft = 0;
int tmpright = 0;
if(root->left)
{
tmpleft = maxPath(root->left,maxresult);
}
if(root->right)
{
tmpright = maxPath(root->right,maxresult);
}
int path = root->val;
if(tmpleft > 0)
{
path = path + tmpleft;
}
if(tmpright > 0)
{
path = path + tmpright;
}
maxresult = max(maxresult, path);
return max(max(tmpleft,tmpright),0) + root->val;
}
int maxPathSum(TreeNode *root) {
int maxresult = (1<<31);
int r = maxPath(root, maxresult);
return maxresult;
}
};