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
.
解题思路:要求的是结果最大的那条路径,考虑递归遍历左右子数。
注意的地方为子树的返回值,返回的值为一条路径的最大值为max(根节点,max(根节点+左子树最大路径,根节点+右子树最大路径))
/**
* 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 maxVal = INT_MIN;
int maxPathSum(TreeNode *root) {
if(root ==NULL){
return 0;
}
maxChildSum(root);
return maxVal;
}
int maxChildSum(TreeNode *root){
int value = root->val;
int lmax = 0;
int rmax = 0;
if(root->left){
lmax = maxChildSum(root->left);
if(lmax >=0)
{
value += lmax;
}
}
if(root->right){
rmax = maxChildSum(root->right);
if(rmax >=0)
{
value += rmax;
}
}
if(value > maxVal){
maxVal = value;
}
return max(root->val,max(root->val + lmax, root->val + rmax));
}
};