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

【Lintcode】094.Binary Tree Maximum Path Sum

时间:2017-05-09 21:39:12      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:htm   pre   www   bin   pat   div   com   root   span   

题目:

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

标签:htm   pre   www   bin   pat   div   com   root   span   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!