Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
方法一:我的思路,采用后序遍历算法int maxPath(TreeNode*root,int &sum),返回值返回子树根节点到叶子节点(可能不一定到叶子节点)路径最大的值,这条路径可能只有根节点(这种情况左右子树最大路径值都为复制)。sum变量保存节点的最大路径值
/**
*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 sum=INT_MIN;
maxPath(root,sum);
return sum;
}
int maxPath(TreeNode* root,int &sum)//返回值该保存什么值?应该保存二叉树路径和的最大值。
{
if(root==NULL)
{
return 0;
}
int left=maxPath(root->left,sum);
int right=maxPath(root->right,sum);
int sum1=max(left+right,max(left,right))+root->val;
// int sum2=max(sum1,root->val);//有可能根节点很大,
sum=max(sum, max(sum1,root->val));
return max(root->val,(max(left,right)+root->val));
}
};
方法二:19ms优化版本(leedcode大神级的方案),将最大路径为负值的值置为,0,当根节点的左子树和右子树的最大路径值都为负值时,此时根节点的最大路径值即为根节点的值,若左子树和右子树有一个不为零,则根节点的最大路径为根节点的值加上左子树和右子树中最大路径不为零的那一颗子树的最大路径值。可以避免比较大小
体会一下如何优化的。if(l<0) l=0;可以避免比较大小。
class Solution {
public:
int maxToRoot(TreeNode* root, int& re){
if(!root){return 0;}
int l = maxToRoot(root->left,re);
int r = maxToRoot(root->right,re);
if(l<0){l=0;}
if(r<0){r=0;}
if(l+r+root->val > re){re = l+r+root->val;}
return root->val + max(l,r);
}
int maxPathSum(TreeNode* root) {
int max = INT_MIN;
maxToRoot(root,max);
return max;
}
};