Binary Tree Maximum Path Sum

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

Return 6.

这个题不算难,不过有一个陷阱,输入会有负数,这个我一开始没有考虑到.因为负数的关系,这个题里面就不可以随意用零垫底了,要考虑一下细节.

class Solution {
private:
	int max(int a, int b)
	{
		return a > b ? a : b;
	}
	
	int searchMax(int &x, TreeNode *root)
	{
		if(root->left == NULL && root->right == NULL)
		{
			x = root->val;
			return root->val;
		}
		if(root->left != NULL && root->right != NULL)
		{
			int a, b = searchMax(a, root->left);
			int c, d = searchMax(c, root->right);
			x = max(max(a, c), root->val + max(b, 0) + max(d, 0));//这里和下面都以root->val作垫底值
			return root->val + max(max(b, d), 0);
		}
		TreeNode *t = root->left == NULL ? root->right : root->left;
		int a, b = searchMax(a, t);
		x = max(a, root->val + max(b, 0));
		return root->val + max(b, 0);
	}
public:
    int maxPathSum(TreeNode *root) {
		int a;
		searchMax(a, root);
		return a;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值