您的位置:首页 > 其它

Binary Tree Maximum Path Sum

2013-11-23 13:38 323 查看
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
.

思路:

递归调用函数。用函数comput计算从子树到根节点传递到根节点的父节点的值,然后用一个result记录在递归过程中求得的最大值。

代码:

int max(int a, int b){
if(a > b)
return a;
return b;
}
int comput(TreeNode *root, int &result){
if(root == NULL)
return 0;
int left = comput(root->left, result);
int right = comput(root->right, result);
int arch = left + right + root->val;
int valToParent = max(root->val, root->val+max(left, right));
result = max(result, max(arch, valToParent));
return valToParent;
}
int maxPathSum(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int result = INT_MIN;
comput(root, result);
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: