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

Binary Tree Maximum Path Sum--LeetCode

时间:2015-04-09 11:52:49      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   算法   

题目:

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

标签:leetcode   c++   算法   

原文地址:http://blog.csdn.net/yusiguyuan/article/details/44957695

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