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
.
这个是计算树的节点,从一个点到另外一个节点的路径上最大的和,算是求最优解 。
节点当中会有负数,所以不能简单的进行节点子树的最大值相加。
1.递归求解,如果这个节点的没有子树,那么这个节点的最大值就是它自己。
在有子树的情况下,这个节点有多条路径的和可以比较,(1)左子树的最大和;(2)左子树和自己的最大和,(3)右子树的最大和,(4)右子树和自己的最大和;(5)左子树和自己和右子树的和;这四个值中最大的和总的最大值比较,并进行相应替换。返回的值只可能是(2)和(4)当中最大的
2.这样最大值就会出现。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int res;
int maxPathSum(TreeNode *root) {
if(root==NULL)
{
return 0;
}
res = root->val;
countSubTree(root);
return res;
}
int countSubTree(TreeNode *sub)
{
int root = sub->val;
int left =0,right = 0;
if(sub->left!=NULL)
{
left = countSubTree(sub->left);
res = res>left?res:left;
}
if(sub->right!=NULL)
{
right = countSubTree(sub->right);
res = res>right?res:right;
}
int sumLeft = root+left;
int sumRight = root+right;
int allSum = root+left+right;
int maxNum = max(max(sumLeft,sumRight),root);
res = max(max(res,maxNum),allSum);
return maxNum;
}
};