您的位置:首页 > 其它

leetcode---binary-tree-maximum-path-sum---树

2017-10-06 16:11 417 查看
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

Return6.

/**
* 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 ans;
int dfs(TreeNode *root)
{
if(!root)
return 0;
int lmax = dfs(root->left);
int rmax = dfs(root->right);
int v = max(root->val, max(root->val+lmax, root->val+rmax));
int v1 = max(v, root->val+lmax+rmax);
if(v1 > ans)
ans = v1;
return v;
}

int maxPathSum(TreeNode *root)
{
ans = INT_MIN;
dfs(root);
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: