首页 > 代码库 > Binary Tree Maximum Path Sum

Binary Tree Maximum Path Sum

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