1. 程式人生 > >Binary Tree Maximum Path Sum 二叉樹中任意路徑的最大和

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.

/**
 * 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 maxRes;
    int maxPathSum(TreeNode* root) {
        maxRes=INT_MIN;
        solve(root);
        return maxRes;
    }
    
    int solve(TreeNode *root){
        int ans=INT_MIN;//返回當前的最大值
        if(root==NULL){
            return ans;
        }else if(root->left==NULL){// 只有一個節點
            int tmp=solve(root->right);
            ans= tmp<0?root->val:(root->val+tmp);//返回當前的最大值
            if(ans > maxRes){//更新整個最大值
                maxRes = ans;
            }
        }else if(root->right==NULL){
            int tmp=solve(root->left);
            ans = tmp<0?root->val:(root->val+tmp);//返回當前的最大值
            if(ans > maxRes){//更新整個最大值
                maxRes = ans;
            }
        }else {
            
            int leftMax=solve(root->left);
            int rightMax=solve(root->right);
            int maxTmp=leftMax<rightMax?rightMax:leftMax;
            ans = maxTmp<0?root->val:(maxTmp+root->val);//返回當前的最大值
            
            if(ans > maxRes){//1個節點和根節點,更新整個最大值
                maxRes = ans;
            }
            if((leftMax+rightMax+root->val) > maxRes){//兩個節點時,更新整個最大值
                maxRes=leftMax+rightMax+root->val;
            }
        }
        return ans;
    }
};