首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。