leetcode124. 二叉树中的最大路径和

给定一个非空二叉树,返回其最大路径和。

本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不需要经过根节点。

示例 1:

输入: [1,2,3]

       1
      / \
     2   3

输出: 6

示例 2:

输入: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

输出: 42

解题思路:

没想到用递归来计算子树的和,思路很巧妙。

class Solution {
public:
    int maxv=-123123632;
    int maxPathSum(TreeNode* root) {
        if(root==NULL)
            return 0;
        calc(root);
        return maxv;
    }
    
    
    int calc(TreeNode* root)
    {
        if(root==NULL)
            return 0;
        int temp=root->val;
        int lmaxsum=calc(root->left);
        int rmaxsum=calc(root->right);
        
        if(lmaxsum>0)
            temp+=lmaxsum;
        if(rmaxsum>0)
            temp+=rmaxsum;
        
        if(temp>maxv)
            maxv=temp;
        
        //返回以当前节点为根节点的子树的和
        return max(root->val,max(root->val+lmaxsum,root->val+rmaxsum));
            
    }
};


猜你喜欢

转载自blog.csdn.net/zhuixun_/article/details/80519381