您的位置:首页 > 其它

124. Binary Tree Maximum Path Sum

2016-11-16 20:06 260 查看
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 must contain at least one node and does not need to go through the root.

For example:

Given the below binary tree,

1
/ \
2   3


Return 6.

思路:

求最大路径和就等于下面三个值的最大值:

左子树的最大路径和

右子树最大路径和

左子树单路 + 右子树单路 + root.val

如果只是一个节点,那么当然就是这个节点的值了.

如果这个作为root,那么最长路应该就是left+ right+root->val.

当然如果left,或者right<0就不用加了.

最大值是一个全局变量,如果当前路径最大值大于最大值则更新。

class Solution {
public:
int MaxValue=INT_MIN;
int maxPathSum(TreeNode* root)
{
if(!root)
return 0;
dfs(root);
return MaxValue;
}
int dfs(TreeNode *root)
{
if(!root)
return 0;
int cur=root->val;
int leftmax=dfs(root->left);
int rightmax=dfs(root->right);
if(leftmax>0)
cur+=leftmax;
if(rightmax>0)
cur+=rightmax;
if(cur>MaxValue)
MaxValue=cur;
return max(root->val,max(root->val+leftmax,root->val+rightmax));
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  深度优先遍历