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
题目:求任意两个结点间路径的最大和
解题思路:后续遍历二叉树 与 动态规划(一维数组求最大连续子数组和)结合运用。
.
int innerMaxPathSum(TreeNode *root, int &maxValue){
int v = root->val;
int l, r;
maxValue = max(v, maxValue);
if(NULL == root->left && NULL == root->right){
return v; //左右子数都为空 即叶结点的情况 直接返回其值
}
if(NULL == root->right){ //只有左子树的情况
l = innerMaxPathSum(root->left, maxValue);
maxValue = max(l, maxValue);
maxValue = max(v + l, maxValue);
return max(v, l + v); //该种情况返回必须包含根结点的路径的最大值, 如果左加根比根小则丢弃根
}
if(NULL == root->left){
r = innerMaxPathSum(root->right, maxValue);
maxValue = max(r, maxValue);
maxValue = max(v + r, maxValue);
return max(v, r + v);//同左
}
l = innerMaxPathSum(root->left, maxValue);
r = innerMaxPathSum(root->right, maxValue);
int oneMaxSum = max(l, r);
maxValue = max(oneMaxSum, maxValue);
int twoMaxSum = max(l + v, v + r);
maxValue = max(twoMaxSum, maxValue);
maxValue = max(l + v + r, maxValue);
return max(twoMaxSum, v); //同理要包含根结点, 此时有三种情况,要么是根,要么是根左,要么是根右
}
int maxPathSum(TreeNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int maxValue = root->val;
innerMaxPathSum(root, maxValue);
return maxValue;
}