首页 > 其他 > 详细

[LeetCode] Binary Tree Maximum Path Sum

时间:2015-08-04 22:38:13      阅读:245      评论:0      收藏:0      [点我收藏+]

A relatively difficult tree problem. Well, a recursive solution still gives clean codes. The tricky part of this problem is how to record the result. You may refer to this link for a nice solution. The code is rewritten as follows.

class Solution {
public:
    int maxPathSum(TreeNode* root) {
        sum = INT_MIN;
        pathSum(root);
        return sum;
    }
private:
    int sum;
    int pathSum(TreeNode* node) {
        if (!node) return 0;
        int left = max(0, pathSum(node -> left));
        int right = max(0, pathSum(node -> right));
        sum = max(sum, left + right + node -> val);
        return max(left, right) + node -> val;
    }
};

 

[LeetCode] Binary Tree Maximum Path Sum

原文:http://www.cnblogs.com/jcliBlogger/p/4703234.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!