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.

思路:

本题的一个难点在于,它不是从最上到最下,所以不是深搜。

另外我卡主的地方在于,函数返回的问题和更新res的问题。

函数返回的应该是本节点加上左右最大值,当然左右还要和0做一个对比的。至于更新呢,则要加上左右节点值已经本节点。这是不同的地方。

代码:

/**
 * 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 maxPathSum(TreeNode* root) {
        int res=INT_MIN;
        maxPath( root,res);
        
        return res;
    }
    
    int maxPath(TreeNode *root,int &res){
        if(root==NULL)  return 0;
        //res代表当前最大值
        
        int left=maxPath(root->left,res);
        int right=maxPath(root->right,res);
        
        int tem=root->val+(left>0?left:0)+(right>0?right:0);
        res=tem>res?tem:res;
        //首先tem的功能就是左边加上节点加上右节点,更新整体的res值。
        //至于函数返回值,返回的应该是加上本节点与左右子树的最大值。
        //函数的意思是从本节点到某一个节点的最大值,一定有本节点。
        return root->val+max(left,max(right,0));
    }
};


posted @ 2015-11-16 10:42  JSRGFJZ6  阅读(106)  评论(0编辑  收藏  举报