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

[LeetCode] Binary Tree Maximum Path Sum

时间:2015-08-04 22:41:28      阅读:92      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!