geeksforgeeks Find the maximum path sum between two leaves of a binary tree

Geeksforgeeks上面的一道题: http://www.geeksforgeeks.org/find-maximum-path-sum-two-leaves-binary-tree/

Geeksforgeeks题目描述和解答已经非常清楚,只是那里的实现有bug,见后面的评论。在所有节点val为负或者只有一条边其 val为负的情况下,原实现都返回错误结果。原因是为空的时候返回0这个简单设想覆盖了正确答案。尽管很多人指出了这个问题,但截止目前(2014/7/27),geeksforgeeks还没有更正。

#include <iostream>
using namespace std;

// #define INT_MIN     (-2147483647 - 1)

struct TreeNode
{
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode (int val)
	{
		this->val = val;
		this->left = NULL;
		this->right = NULL;
	}
};

class Solution {
public:
	int maxPathSum(TreeNode *root)
	{
		int maxsum = INT_MIN;
		maxPathSum(root, maxsum);
		return maxsum;
	}

	int maxPathSum(TreeNode *root, int &maxsum)
	{
		if (root->left == NULL && root->right == NULL)
		{
			maxsum = max(maxsum, root->val);
			return root->val;
		}
		else if (root->left == NULL)
		{
			int r = maxPathSum(root->right, maxsum);
			maxsum = max(maxsum, r);
			return root->val + r;
		}
		else if (root->right == NULL)
		{
			int l = maxPathSum(root->left, maxsum);
			maxsum = max(maxsum, l);
			return l + root->val;
		}
		else
		{
			int l = maxPathSum(root->left, maxsum);
			int r = maxPathSum(root->right, maxsum);
			maxsum = max(maxsum, l + root->val + r);
			return max(l, r) + root->val;
		}
	}

	void printTree(TreeNode *root)
	{
		if (root)
		{
			cout<<root->val<<endl;
			printTree(root->left);
			printTree(root->right);
		}
	}
};

int main()
{
	// TreeNode *root = new TreeNode(-15);
	// root->left = new TreeNode(5);
	// root->right = new TreeNode(6);
	
	// root->left->left = new TreeNode(-8);
	// root->left->right = new TreeNode(1);
	// root->left->left->left = new TreeNode(2);
	// root->left->left->right = new TreeNode(6);

	// root->right->left = new TreeNode(3);
	// root->right->right = new TreeNode(9);
	// root->right->right->right = new TreeNode(0);
	// root->right->right->right->left = new TreeNode(4);
	// root->right->right->right->right = new TreeNode(-1);
	// root->right->right->right->right->left = new TreeNode(10);

	// TreeNode *root = new TreeNode(-3);
	// printTree(root);

	TreeNode *root = new TreeNode(-3);
	root->right = new TreeNode(8);
	root->left = new TreeNode(4);

	Solution s;
	cout<<s.maxPathSum(root)<<endl;

	return 0;
}


你可能感兴趣的:(geeksforgeeks Find the maximum path sum between two leaves of a binary tree)