Binary Tree Maximum Path Sum

题目描述:

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.

For example:
Given the below binary tree,

       1
      / \
     2   3

Return 6.

解题思路:

这道题要求的是二叉树上任意两个结点构成的路径和的最大值。

因此可以对于每个结点保存两个变量:localMax和pathMax,
localMax表示的是以该结点为根结点的子树能获得的最大路径和;
pathMax表示包含从当前结点开始向左子树或者右子树延伸能够获得的最大路径和;
然后采用后序遍历的方法得到每个结点的这两个变量。


AC代码如下:

class Solution {
public:
	void getLocalMax(TreeNode* root, int& localMax, int& pathMax)
	{
		if (root == NULL){
			localMax = numeric_limits<int>::min();
			pathMax = numeric_limits<int>::min();
			return;
		}
		int localMaxLeft, pathMaxLeft;
		int localMaxRight, pathMaxRight;
		localMaxLeft = pathMaxLeft = localMaxRight = pathMaxRight = 0;
		getLocalMax(root->left, localMaxLeft, pathMaxLeft);
		getLocalMax(root->right, localMaxRight, pathMaxRight);
		if (localMaxLeft != numeric_limits<int>::min() && localMaxRight != numeric_limits<int>::min()){
			int pathMaxTmp = max(max(pathMaxLeft, pathMaxRight), pathMaxLeft + pathMaxRight);
			localMax = max(max(localMaxLeft, localMaxRight), pathMaxTmp + root->val);
			pathMax = max(pathMaxLeft, pathMaxRight) + root->val;
		}
		else if (localMaxLeft != numeric_limits<int>::min()){
			localMax = max(localMaxLeft, pathMaxLeft + root->val);
			pathMax = pathMaxLeft + root->val;
		}
		else if (localMaxRight != numeric_limits<int>::min()){
			localMax = max(localMaxRight, pathMaxRight + root->val);
			pathMax = pathMaxRight + root->val;
		}
		else{
			localMax = root->val;
			pathMax = root->val;
		}
		localMax = max(localMax, root->val);
		pathMax = max(pathMax, root->val);
	}

	int maxPathSum(TreeNode* root)
	{
		if (root == NULL) return 0;
		int globalMax;
		int localMaxLeft, pathMaxLeft;
		int localMaxRight, pathMaxRight;
		localMaxLeft = pathMaxLeft = localMaxRight = pathMaxRight = 0;
		getLocalMax(root->left, localMaxLeft, pathMaxLeft);
		getLocalMax(root->right, localMaxRight, pathMaxRight);
		if (localMaxLeft != numeric_limits<int>::min() && localMaxRight != numeric_limits<int>::min()){
			int pathMaxTmp = max(max(pathMaxLeft, pathMaxRight), pathMaxLeft + pathMaxRight);
			globalMax = max(max(localMaxLeft, localMaxRight), pathMaxTmp + root->val);
		}
		else if (localMaxLeft != numeric_limits<int>::min()){
			globalMax = max(localMaxLeft, pathMaxLeft + root->val);
		}
		else if (localMaxRight != numeric_limits<int>::min()){
			globalMax = max(localMaxRight, pathMaxRight + root->val);
		}
		else{
			globalMax = root->val;
		}
		return max(globalMax, root->val);
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值