首页 > 其他 > 详细

【Lintcode】094.Binary Tree Maximum Path Sum

时间:2017-05-09 21:08:47      阅读:179      评论:0      收藏:0      [点我收藏+]

题目:

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

Example

Given the below binary tree:

  1
 / 2   3

return 6.

题解:

Solution 1 ()  from here

class Solution {
public:
    int maxPathSum(TreeNode *root) {
        if (root == NULL) {
            return 0;
        }
        
        int res = INT_MIN; 
        helper(root, res);
        
        return res;
    }
    
    int helper(TreeNode *root, int &res) {
        if (root == NULL) {
            return 0;
        }
        
        int sum = root->val;
        int leftMax = helper(root->left, res);
        int rightMax = helper(root->right, res);
        
        if (leftMax > 0) {
            sum += leftMax;
        }
        if (rightMax > 0) {
            sum += rightMax;
        }
        
        res = max(sum, res);
        
        return max(0, max(leftMax, rightMax)) + root->val;
    }    
};

 

【Lintcode】094.Binary Tree Maximum Path Sum

原文:http://www.cnblogs.com/Atanisi/p/6832653.html

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