My solutions works fine on local , please help!


#1

/**

  • Definition for binary tree

  • class TreeNode {

  • int val;
    
  • TreeNode left;
    
  • TreeNode right;
    
  • TreeNode(int x) {
    
  •  val = x;
    
  •  left=null;
    
  •  right=null;
    
  • }
    
  • }
    */
    public class Solution {

    static int preOrderIndex=0;

    public TreeNode buildTree(int A[], int B[]) {

     return BuildTreeHelper(A,B,0,(A.length-1));
    

    }

    private TreeNode BuildTreeHelper(int preOrder[], int inOrder[], int start,int end )
    {
    if(start > end)
    {
    return null;
    }

     int currentData=preOrder[preOrderIndex];
     preOrderIndex++;
     
     TreeNode newNode=new TreeNode(currentData);
     
     if(start == end)
         {
             return newNode;
         }
     
     int dividingIndex=index(inOrder,currentData);
     
     newNode.left=BuildTreeHelper(preOrder,inOrder,start,dividingIndex-1);
     
     newNode.right=BuildTreeHelper(preOrder,inOrder,dividingIndex+1,end);
    
     return newNode;
    

    }

    private static int index(int arr[], int val)
    {
    for(int i= 0;i<arr.length;i++)
    {
    if(arr[i]==val)
    {
    return i;
    }
    }
    return -1;
    }
    }


#2

It’s because you are using a static variable in a function.
While running different test cases value of the static variable ‘preOrderIndex’ never gets reset.
Use global variable instead.