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

leetcode@ [124] Binary Tree Maximum Path Sum (DFS)

时间:2016-01-04 13:19:32      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/binary-tree-maximum-path-sum/

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.

For example:
Given the below binary tree,

       1
      /      2   3

 

Return 6.

技术分享
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int res = INT_MIN;
    
    int dfs(TreeNode* root) {
        if(!root) return 0;
        
        int l = dfs(root->left);
        int r = dfs(root->right);
        
        int rhs = root->val;
        if(l > 0) rhs += l;
        if(r > 0) rhs += r;
        res = max(res, rhs);
        
        return max(l, r) <= 0? root->val: max(l, r) + root->val; 
    }
    
    int maxPathSum(TreeNode* root) {
        if(!root) return 0;
        
        dfs(root);
        
        return res;
    }
};
View Code

 

leetcode@ [124] Binary Tree Maximum Path Sum (DFS)

标签:

原文地址:http://www.cnblogs.com/fu11211129/p/5098419.html

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