您的位置:首页 > 其它

Binary Tree Maximum Path Sum

2015-07-31 22:22 218 查看
原题:Binary Tree Maximum Path Sum

来自leetcode:https://leetcode.com/problems/binary-tree-maximum-path-sum/

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
.
解:

/**
* 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 getMax(TreeNode * root, int &ans){
if(root==NULL)
return 0;
//需要跟0比较,保证左链大于等于0
int left_chain=max(0, getMax(root->left, ans));
int right_chain=max(0, getMax(root->right, ans));

//需要跟0比较,且前面保证了left_chain以及right_chain大于等于0
ans=max(0, left_chain+root->val+right_chain);

//仍然要返回以当前根节点的左右子链和的最大值,因为root不一定是根节点,只有真正的根节点才可以返回
return max(left_chain+root->val, right_chain+root->val);
}

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