Leetcode: Binary Tree Maximum Path Sum

思路:

1. 对于每一个节点, 返回其所在子树所能提供的最大值, 且该最大值必须是单支的, WA 过

2. max(0, max(lf, rt))+root->val, 可以仅返回根节点, WA 过

3. 需要维护一个全局最优解 ans, WA 过

代码:

class Solution {
public:
	int ans;
	int solve_dp(TreeNode *root) {
		if(root == NULL)
			return 0;

		int sum = root->val;
		int lf = 0, rt = 0;
		if(root->left)
		lf = solve_dp(root->left);
		
		if(root->right) 
		rt = solve_dp(root->right);
		if(lf > 0)
			sum += lf;
		if(rt > 0)
			sum += rt;

		ans = max(ans, sum);
		return max(0, max(lf, rt))+root->val;
	}
    int maxPathSum(TreeNode *root) {
		ans = -100000000;
		solve_dp(root);
		return ans;
    }
};

  

posted @ 2013-12-05 12:05  SangS  阅读(494)  评论(0编辑  收藏  举报