标签:
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; } }
标签:
原文地址:http://www.cnblogs.com/Kai-Xing/p/3983500.html