1. 程式人生 > >leetcode124. 二叉樹中的最大路徑和

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));
            
    }
};