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

二叉树最大路径和-Binary Tree Maximum Path Sum

时间:2015-09-22 23:14:20      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

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 binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
int findMax(TreeNode *root,int &res)
{
        if(root==NULL)return 0;
        int value=root->val;
        int left=findMax(root->left,res);
        int right=findMax(root->right,res);
        value+=left>0?left:0;
        value+=right>0?right:0;
        res=value>res?value:res;
        return max(root->val,max(root->val+left,root->val+right));    
}
    int maxPathSum(TreeNode *root) {
        int res=INT_MIN;
        findMax(root,res);
        return res;
    }
};

  

二叉树最大路径和-Binary Tree Maximum Path Sum

标签:

原文地址:http://www.cnblogs.com/Vae1990Silence/p/4830620.html

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