leetcode之Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1
      / \
     2   3

Return 6.

這道題一開始沒看懂題目什麼意思,後來才明白是:把樹看成是無向圖,求一條路徑,使得這條路徑上結點val之和最大(此路徑的val之和稱爲最大路徑和),當然路徑可以只含一個點。

tempMax保存當前找到的最大路徑和,基於二叉樹的遍歷(深度優先),如下

getMax(*root)返回以root爲根的子樹中包含root且最多隻包含root的一個子分支的路徑的最大路徑和(是個局部值),這個函數中會修改最大路徑和tempMax。

maxL爲左子樹的最大路徑和,

maxR爲右子樹的最大路徑和,

如果val+max(0,maxL,maxR,maxL+maxR)>tempMax,那麼更新tempMax

返回val +max(maxL,maxR,0) ,注意只能最多包含一個分支,否則包含兩個分支的話,路徑就確定了,返回給上層就不能再構建路徑。


最後tempMax即爲所求。

代碼如下:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    static int tempMax;
    /*返回包含本結點的最大路徑*/
    int getMax(TreeNode *root){
        if(NULL==root)
            return 0;
        if(!root->left&&!root->right){/*leaf node*/
            tempMax=root->val>tempMax?root->val:tempMax;
            return root->val;
        }
        int maxL=getMax(root->left);
        int maxR=getMax(root->right);
        int maxLR=std::max(maxL,maxR);
        int maxLR2=std::max(maxLR,maxL+maxR);
        int m=maxLR2>0?root->val+maxLR2:root->val;
        /*update tempMax*/
        tempMax=m>tempMax?m:tempMax;
        return maxLR>0?root->val+maxLR:root->val;
        
    }
    int maxPathSum(TreeNode *root) {
        tempMax=INT_MIN;
        getMax(root);
        /*return tempMax*/
        return tempMax;
    }
};
int Solution::tempMax=INT_MIN;





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章