leetcode4: 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.

key-points: globe variable record the max value of local branch.

at the end, in root node compare max value cross root node with maxmum local branch which may not cross root node.

 

 

/**
 * 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(TreeNode * root, int & globe_max){
        if(!root) {
            return 0;
        }
        
        globe_max = max( root->val, globe_max);
        
        int local_max = root->val;
        int left = maxSum(root->left, globe_max);
        int right = maxSum(root->right, globe_max);
        
        if(left>0) local_max +=left;
        if(right>0) local_max += right;
        
        globe_max = max(globe_max, local_max);
        
        int rVal = root->val;
        return max(rVal, max(rVal+right, rVal+left) );
    }

    int maxPathSum(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int globe_max = root->val;
        int maxVal = maxSum(root, globe_max);
        
        return max(globe_max, maxVal);
        
    }
};

 

 



/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    int globe = Integer.MIN_VALUE;
// null, {1}, {-1}, {0} , {1,-2,-3}, {-1,#,2,-3,0} {1,#,2,3,#,4,5,6}    
    public int maxPathSum(TreeNode root) {
        // Start typing your Java solution below
        // DO NOT write main() function
        
        //input check
        globe = Integer.MIN_VALUE;
        
        int passRoot = maxRec(root);
        
        return globe>passRoot ? globe : passRoot;  //Math.max(globe, passRoot) instead. 
    }
    
    private int maxRec(TreeNode root){
        if(root==null) return 0;
        
        int l = maxRec(root.left);
        int r = maxRec(root.right);
        
        int local = root.val;
        if(l>0) local += l;
        if(r>0) local += r;
        
        globe = globe>local ? globe : local;
        
        return Math.max( root.val, Math.max( root.val+l, root.val+r) );
    }
}


 

posted @ 2012-12-20 15:38  西施豆腐渣  阅读(155)  评论(0编辑  收藏  举报