题目描述:
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);
}
};