Thursday, September 25, 2014

[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.


Analysis:

/**
 * 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 helper(TreeNode* root, int& maxSum)
    {
        if (root == NULL)
            return 0;
        else
        {
            int leftSum = helper(root->left, maxSum);
            int rightSum = helper(root->right,maxSum);
            
            int sum = root->val;
            if (leftSum > 0)
                sum += leftSum;
            if (rightSum > 0)
                sum += rightSum;
            
            maxSum = max(maxSum, sum);
            
            return max(leftSum, rightSum) > 0 ? max(leftSum, rightSum) + root->val : root->val;
        }
    }

    int maxPathSum(TreeNode *root) {
        int sum = INT_MIN;
        helper(root, sum);
        
        return sum;
    }
};

No comments:

Post a Comment