Weird test case stuck: right answer in eclipse, wrong output in OJ

  • 0
    public static int maxLeafPath = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        if(root == null) return 0;
        int rst = root.val;
        int maxLeft, maxRight;
        if((maxLeft = maxLeaf(root.left)) > 0) rst += maxLeft;
        if((maxRight = maxLeaf(root.right)) > 0) rst += maxRight;
        return Math.max(rst, maxLeafPath);
    int maxLeaf(TreeNode root){
        if(root == null) return 0;
        int subPath = root.val;
        int maxLeft, maxRight;
        if((maxLeft = maxLeaf(root.left)) > 0) subPath += maxLeft;
        if((maxRight = maxLeaf(root.right)) > 0) subPath += maxRight;
        if(subPath > maxLeafPath) maxLeafPath = subPath;
        return Math.max(maxLeft, maxRight) <= 0 ? root.val : root.val + Math.max(maxLeft, maxRight); 

    Input: {-2,1}
    Output: 2
    Expected: 1

    When the test case is {-2, 1}, I got the right answer in eclipse, that's 1. However, it outputs 2 in OJ.
    I carefully checked my code for a couple of times, and I am pretty sure it is correct.

    I don't know what's wrong with it. Is it possible that I can't use global variable such as
    "public static int maxLeafPath = Integer.MIN_VALUE;" in online judge?

    Could anyone help me figure out this puzzling problem?

    Thanks in advance.

  • 0

    Hey guys,

    I removed the global variable and wrapped it as an argument to implement the method.
    And it turns out to be correct.

    I guess the compiler of Online Judge is different from eclipse's. Thus be careful to use global variable in java while using online judges.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.