1. 程式人生 > >124. Binary Tree Maximum Path Sum

124. 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 must contain at least one node and does not need to go through the root.

解題思路:

樹結構顯然用遞迴來解,解題關鍵:

1、對於每一層遞迴,只有包含此層樹根節點的值才可以返回到上層。否則路徑將不連續。

2、返回的值最多為根節點加上左右子樹中的一個返回值,而不能加上兩個返回值。否則路徑將分叉。

在這兩個前提下有個需要注意的問題,最上層返回的值並不一定是滿足要求的最大值,

因為最大值對應的路徑不一定包含root的值,可能存在於某個子樹上。

因此解決方案為設定全域性變數maxSum,在遞迴過程中不斷更新最大值。

實驗程式碼:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxSum;
    Solution()
    {
        maxSum = INT_MIN;
    }
    int maxPathSum(TreeNode* root)
    {
        Helper(root);
        return maxSum;
    }
    int Helper(TreeNode *root) {
        if(!root)
            return INT_MIN;
        else
        {
            int left = Helper(root->left);
            int right = Helper(root->right);
            if(root->val >= 0)
            {//allways include root
                if(left >= 0 && right >= 0)
                    maxSum = max(maxSum, root->val+left+right);
                else if(left >= 0 && right < 0)
                    maxSum = max(maxSum, root->val+left);
                else if(left < 0 && right >= 0)
                    maxSum = max(maxSum, root->val+right);
                else
                    maxSum = max(maxSum, root->val);
            }
            else
            {
                if(left >= 0 && right >= 0)
                    maxSum = max(maxSum, max(root->val+left+right, max(left, right)));
                else if(left >= 0 && right < 0)
                    maxSum = max(maxSum, left);
                else if(left < 0 && right >= 0)
                    maxSum = max(maxSum, right);
                else
                    maxSum = max(maxSum, max(root->val, max(left, right)));
            }
            //return only one path, do not add left and right at the same time
            return max(root->val+max(0, left), root->val+max(0, right));
        }
    }
};