问题描述:
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,
分析:起初犯了两个错误,第一个错误:将获取到最大值返回。错误,为啥错误?如果将最大值返回,那也许根本就不能形成路径。
换句话说,我们在使用递归:solve(root->left)时,潜在的就要求root->left就是路径中的一个节点,而这个点也许并不在最大路径节点中。所以,此时应该将max作为一个“全局变量”中,在递归过程中,root->val和两侧的值(如果大于0)相加与max值比较。
有没有可能root->val是负值,而root->left或者root->right取正数?有可能,但是我们需要明确递归的含义:在这里,我们递归的含义是:以root节点为连接点时能够获取到的最大值。这就要求在计算最大值时,一定要将root->val加上(不加,还能叫连接点吗)
第二个错误:还是递归返回值的错误,递归的返回值是以该root为关键节点,返回这区域的最大值。因此,返回的应该为:max(root->val,root->val+lmax,root->val+rmax);起初,我还加入了root->val+lmax+rmax作为比较,其实是错误的,因为这就不能形成路径。
这道题很有意思,值得多做两遍。
代码如下:32ms
/**
* 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 {
private:
int max = INT_MIN;
public:
int solve(TreeNode* root){
if(!root)
return 0;
int val = root->val;
int tmp = val;
int lMax = solve(root->left);
int rMax = solve(root->right);
if(lMax>0)
val+=lMax;
if(rMax>0)
val+=rMax;
if(val>max)
max = val;
int res = tmp;
res = res>(tmp+lMax)?res:tmp+lMax;
res = res>(tmp+rMax)?res:tmp+rMax;
return res;
}
int maxPathSum(TreeNode* root) {
solve(root);
return max;
}
};