您的位置:首页 > 其它

Leetcode -- Binary Tree Maximum Path Sum

2015-10-24 08:53 447 查看
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 does not need to go through the root.

For example:

Given the below binary tree,
1
/ \
2   3


Return
6
.
/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxsum=INT_MIN;
int dfs(TreeNode* root)
{
if(root==NULL) return 0;
int left = dfs(root->left);
int right = dfs(root->right);
int sum = root->val;
if(left>0) sum+=left;
if(right>0) sum+= right;
maxsum = max(maxsum,sum);
return max(left,right)>0?max(left,right)+root->val:root->val;
}
int maxPathSum(TreeNode* root) {
dfs(root);
return maxsum;
}
};


分析:

此题中dfs返回的值并不是最终结果,只是单方向路径,而最终的最大和在遍历过程中被计算。

在dfs的过程中,以每个节点为中心计算一次sum,保存其最大值,计算sum的过程中需要左右路径的单方向求和,所以返回此单方向路径和。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: