码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Maximum Path Sum

时间:2014-12-19 21:53:01      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:

class Solution {
public:
    int maxPathSum(TreeNode *root) {
        if(root == NULL) return 0;
        int max_sum = INT_MIN;
        unordered_map<TreeNode *, int> node_order;
        unordered_map<TreeNode *, TreeNode *> parent;
        map<pair<TreeNode *, TreeNode *>, int> distance;
        stack<TreeNode *> S;
        S.push(root);
        parent[root] = NULL;
        int seq = 0;
        
        while(!S.empty()){
            TreeNode * p = S.top();
            S.pop();
            seq++;
            node_order[p] = seq;
            for(auto i = node_order.begin(); i != node_order.end(); i++){
               if(i->first == p)
                    distance.insert(make_pair(make_pair(p,p),p->val));
               else{
                   TreeNode * pra = parent[p];
                   if(pra != NULL){
                       int tmp;
                       if(node_order[pra] <= node_order[i->first]){
                           tmp = distance[make_pair(pra,i->first)] + p->val;
                       }else{
                           tmp = distance[make_pair(i->first,pra)] + p->val;
                       }
                       distance.insert(make_pair(make_pair(i->first,p),tmp));
                       if(tmp > max_sum) max_sum = tmp;
                   }
               }
            }
            
            if(p->right){
                S.push(p->right);
                parent[p->right] = p;
            }
            if(p->left){
                S.push(p->left);
                parent[p->left] = p;
            }
        }
        
        return max_sum;
    }
}

Binary Tree Maximum Path Sum

标签:

原文地址:http://www.cnblogs.com/Kai-Xing/p/3983500.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!