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
.
tempMax保存当前找到的最大路径和,基于二叉树的遍历(深度优先),如下
getMax(*root)返回以root为根的子树中包含root且最多只包含root的一个子分支的路径的最大路径和(是个局部值),这个函数中会修改最大路径和tempMax。
maxL为左子树的最大路径和,
maxR为右子树的最大路径和,
如果val+max(0,maxL,maxR,maxL+maxR)>tempMax,那么更新tempMax
返回val +max(maxL,maxR,0) ,注意只能最多包含一个分支,否则包含两个分支的话,路径就确定了,返回给上层就不能再构建路径。
最后tempMax即为所求。
代码如下:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
static int tempMax;
/*返回包含本结点的最大路径*/
int getMax(TreeNode *root){
if(NULL==root)
return 0;
if(!root->left&&!root->right){/*leaf node*/
tempMax=root->val>tempMax?root->val:tempMax;
return root->val;
}
int maxL=getMax(root->left);
int maxR=getMax(root->right);
int maxLR=std::max(maxL,maxR);
int maxLR2=std::max(maxLR,maxL+maxR);
int m=maxLR2>0?root->val+maxLR2:root->val;
/*update tempMax*/
tempMax=m>tempMax?m:tempMax;
return maxLR>0?root->val+maxLR:root->val;
}
int maxPathSum(TreeNode *root) {
tempMax=INT_MIN;
getMax(root);
/*return tempMax*/
return tempMax;
}
};
int Solution::tempMax=INT_MIN;