Saturday, February 8, 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.

Solution:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    int maxValue;
    public int maxPathSum(TreeNode root) {
        maxValue = Integer.MIN_VALUE;
        maxPathSumRec(root);
        return maxValue;
    }
    
    public int maxPathSumRec(TreeNode root) {
        if(root==null )
        {
            return 0;
        }
        int leftTree = maxPathSumRec(root.left);
        int rightTree = maxPathSumRec(root.right);
        if (leftTree<0 && rightTree<0)
        {
            maxValue = Math.max(maxValue,root.val);
            return root.val;
        }
        //MaxValue dodging in this node
        if(leftTree>0 && rightTree>0)
            maxValue = Math.max(maxValue,root.val+ leftTree + rightTree);
        int max= Math.max(leftTree, rightTree)+ root.val;
        maxValue = Math.max(maxValue,max);
        return max;
    }
    
}

No comments :

Post a Comment