Saturday, August 31, 2013

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
/**
 * 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 setmax(TreeNode *root, int &maxv)
{
    if(!root) return 0;
        
    int leftmax  = setmax(root->left, maxv);
    int righmax  = setmax(root->right, maxv);
    
    int maxp = root->val;
    if(leftmax > 0) maxp += leftmax;
    if(righmax > 0)  maxp += righmax;
    
    maxv = max(maxv, maxp);
    return max(root->val, root->val+  max(leftmax, righmax));
}

int maxPathSum(TreeNode *root) {
     if(!root)
                return 0;
    int maxc  =  root->val;
    setmax(root, maxc);
    return maxc;
}

};

No comments:

Post a Comment