题解 | #二叉树中的最大路径和#

二叉树中的最大路径和

http://www.nowcoder.com/practice/da785ea0f64b442488c125b441a4ba4a

 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
private:
    int res = INT_MIN;
public:
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    int maxPathSum(TreeNode* root) {
        // write code here
        cal(root);
        return res;
    }
    
    int cal(TreeNode* root){
        if(root == nullptr){
            return 0;
        }
        
        int max_left = cal(root->left);
        int max_right = cal(root->right);
        
        int cur_res = max(max_left + root->val, max_right + root->val);
        cur_res = max(max_left + max_right + root->val, cur_res);
        cur_res = max(root->val, cur_res);
        res = max(cur_res, res);
        
        return max(max(max_left + root->val, max_right + root->val), root->val);
    }
    
};
全部评论

相关推荐

03-04 07:14
门头沟学院 C++
后测速成辅导一两个月...:老板:都给工作机会了还想要工资,哪来这么多好事
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务