您的位置:首页 > 其它

*****(leetcode) Binary Tree Maximum Path Sum (tree)

2014-12-09 10:14 399 查看
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
.

Show Tags

Have you met this question in a real interview?
Yes

No

Discuss

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    struct sumSet{ //用于表示当前节点的最大值集合,最大值有两种:一种是从该节点往下路径,另外一种是左右横跨的路径(可能包含该节点,或该节点的子孩子当中的一条横跨路径。
       int verticalSum; // 垂直路径,包含了该节点,会被计算上层最大值时使用
       int crossSum;//横方向的值,不会被上层计算,但会与上层比较
       sumSet(int x):verticalSum(x), crossSum(x){}
    };
    int max(int a, int b){
        return a>b?a:b;
    }
    int maxSum = 0;
    sumSet* maxFunction(TreeNode *root){
        if(root==NULL)
            return NULL;
        sumSet *set = new sumSet(0);
        sumSet *lSet = maxFunction(root->left);
        sumSet *rSet = maxFunction(root->right);
        if(NULL!=lSet&&NULL!=rSet){//左右子树不为空
            set->crossSum = max((root->val+lSet->verticalSum+rSet->verticalSum), max(rSet->crossSum,lSet->crossSum));
            set->verticalSum = max(rSet->verticalSum,lSet->verticalSum)+root->val;
        }
        if((NULL==lSet&&NULL!=rSet)||(NULL!=lSet&&NULL==rSet)){ //左右子树有一棵为空
            sumSet *tmp = lSet==NULL?rSet:lSet;
            set->crossSum = max((root->val+tmp->verticalSum), tmp->crossSum);
            set->verticalSum =tmp->verticalSum+root->val;
        }
        if(NULL==lSet&&NULL==rSet)
            set->crossSum = set->verticalSum = root->val;
        maxSum = max(maxSum, max(set->crossSum, set->verticalSum)); //maxSum 全局,用于记录过程中的最大值
        if(set->verticalSum<0) //如果该节点的垂直路径值<0, 则该节点往下的路径在上层计算值只能起到副作用(加上该条路径 值会变小,所以置为0, 对上层计算不起影响。
            set->verticalSum=0;
        return set;
    }
public:
    int maxPathSum(TreeNode *root) {
        if(NULL==root)
            return maxSum;
        maxSum=root->val;
        sumSet *ans = maxFunction(root);
        return maxSum;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: