binary-tree-maximum-path-sum

1、题目描述

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

Return6.

2、思路

       此题比较灵活,因为start和end可以是树中的任何一个节点。

       首先,设最终解的路径根节点为A,那么最大路径和就是:节点A的值,加上左子树上的最大路径值(单方向的那种),再加上右子树上的最大路径值(单方向的那种)。当然左右子树上的最大路径值要大于0,否则就不加!比如,上面的例子中要是将2换成-2,那么最终解就变成了4(即1 + 3),因为左子树的最大路径值-2小于0。

       可以看出,其实只要计算出当前节点的左、右子树的最大路径值(单方向的那种),那么以当前节点为根节点的最大路径和(maximum path sum)就可以计算出来了。而计算左、右子树的最大路径值这种操作,可以采用的递归方式来完成,所以递归函数的返回值设为“最大路径值(单方向的那种)”。在递归计算中,是可以把子节点的maximum path sum也计算出来的,所以只要设置一个全局变量maxValue记录下其中最大的maximum path sum就可以了。

3、代码

struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
	int maxValue;
public:
	int maxPathSum(TreeNode *root) {
		maxValue = std::numeric_limits<int>::min();
		helper(root);
		return maxValue;
	}
private:
	int helper(TreeNode *root)
	{
		if (root == NULL)
			return 0;
		int left = helper(root->left);
		int right = helper(root->right);
		int cur = root->val + (left>0 ? left : 0) + (right>0 ? right : 0);
		if (cur > maxValue)
			maxValue = cur;
		return root->val + max(left, max(right, 0));
	}
};

猜你喜欢

转载自blog.csdn.net/ye1215172385/article/details/81109646