您的位置:首页 > 其它

Binary Tree Maximum Path Sum 二叉树中任意路径的最大和

2015-10-07 22:08 459 查看


Binary Tree Maximum Path Sum

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 maxRes;
int maxPathSum(TreeNode* root) {
maxRes=INT_MIN;
solve(root);
return maxRes;
}

int solve(TreeNode *root){
int ans=INT_MIN;//返回当前的最大值
if(root==NULL){
return ans;
}else if(root->left==NULL){// 只有一个节点
int tmp=solve(root->right);
ans= tmp<0?root->val:(root->val+tmp);//返回当前的最大值
if(ans > maxRes){//更新整个最大值
maxRes = ans;
}
}else if(root->right==NULL){
int tmp=solve(root->left);
ans = tmp<0?root->val:(root->val+tmp);//返回当前的最大值
if(ans > maxRes){//更新整个最大值
maxRes = ans;
}
}else {

int leftMax=solve(root->left);
int rightMax=solve(root->right);
int maxTmp=leftMax<rightMax?rightMax:leftMax;
ans = maxTmp<0?root->val:(maxTmp+root->val);//返回当前的最大值

if(ans > maxRes){//1个节点和根节点,更新整个最大值
maxRes = ans;
}
if((leftMax+rightMax+root->val) > maxRes){//两个节点时,更新整个最大值
maxRes=leftMax+rightMax+root->val;
}
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode oj