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
void helper_sum(BinTree* root,vector<int>& path,int& maxsum)
{
if(root == NULL)
return ;
path.push_back(root->value);
if(root->left == NULL && root->right == NULL)
{
int tmp=0;
for(int i=0;i<path.size();i++)
{
tmp += path[i];
cout<<path[i]<<" ";
}
cout<<"tmp is "<<tmp<<endl;
cout<<endl;
maxsum = max(tmp,maxsum);
// cout<<"tmp is "<<tmp<<endl;
//return ;
}
helper_sum(root->left,path,maxsum);
helper_sum(root->right,path,maxsum);
path.pop_back();
}
int MaxPathSum(BinTree* root)
{
if(root == NULL)
return 0;
vector<int> path;
int maxsum=0;
helper_sum(root,path,maxsum);
return maxsum;
}
如果按照题意要求,那么从任意一个节点开始,任意一个节点结束,那么可能会出现下面的情况,最大的路径不经过根节点,最大的路径经过根节点。
如果最大的路径不经过根节点,那么最大的路径要么在左子树中,要么在右子树中,如果经过根节点,那么左子树最大+右子树最大+根节点的值。
最终的结果是取三个之最。
Binary Tree Maximum Path Sum--LeetCode
原文地址:http://blog.csdn.net/yusiguyuan/article/details/44957695