Success while Running Code, fails while submitting the solution


  • 0
    S

    [3,4,5,1,3,null,1]

    This test case is failing while Submitting solution, returning wrong result 15, while expected is 9.

    But if i am running the code with same custom test case "[3,4,5,1,3,null,1]", it is returning me expected 9.

    My Code is here:

    /**

    • Definition for a binary tree node.

    • public class TreeNode {

    • public int val;
      
    • public TreeNode left;
      
    • public TreeNode right;
      
    • public TreeNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      public static int s0 =0;
      public static int s1 = 0;

      public int Rob(TreeNode root) {
      sum(root,0);
      int rob = s1 > s0 ? s1 : s0;
      return rob;
      }

      public void sum(TreeNode root, int level)
      {
      if (root != null)
      {
      if (level == 0)
      {
      sum(root.left,1);
      s0 += root.val;
      sum(root.right,1);
      }
      else if (level == 1)
      {
      sum(root.left,0);
      s1 += root.val;
      sum(root.right,0);
      }
      }
      }

    }


  • 0
    C

    The reason is because of the static variables. Solution is simple: just don't use static variables.


Log in to reply
 

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