您的位置:首页 > 其它

二叉树中的最大路径和

2015-08-01 19:18 405 查看
给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和

/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
class resulttype{
public:
int singlepath;
int maxpath;
resulttype(int x, int y): singlepath(x), maxpath(y)
{}
};
resulttype helper(TreeNode *x){
if (x == nullptr) {
resulttype *m = new resulttype(0, INT_MIN);
return *m;
}
//divide
resulttype left = helper(x -> left);
resulttype right = helper(x -> right);
int sigleft = max(left.singlepath, right.singlepath) + x -> val;
sigleft = max(sigleft, 0);

int maxpa= max(left.maxpath, right.maxpath);
maxpa = max(maxpa, left.singlepath + right.singlepath + x-> val);

resulttype *max = new resulttype(sigleft, maxpa);
return *max;
}
int maxPathSum(TreeNode *root) {
// write your code here
resulttype result= helper(root);
return result.maxpath;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: