Test case 1 and testcase 2 show run error while my code runs fine on eclipse

import java.util.Scanner;

public class Main {

public static class TreeNode {
	int val;
	TreeNode left;
	TreeNode right;

	TreeNode() {
	};

	TreeNode(int val) {
		this.val = val;
	}

	TreeNode(int val, TreeNode left, TreeNode right) {
		this.val = val;
		this.left = left;
		this.right = right;
	}
}

public static void main(String[] args) {
	
	Scanner scn = new Scanner(System.in);
	int n = scn.nextInt();

	int[] preorder = new int[n];
	for (int j = 0; j < n; j++) {
		preorder[j] = scn.nextInt();
	}

	int m = scn.nextInt();
	int[] inorder = new int[m];
	for (int j = 0; j < m; j++) {
		inorder[j] = scn.nextInt();
	}
	
	TreeNode root=buildTree(preorder,inorder);
	display(root);

}
public static int index=0;
public static TreeNode buildTree(int[] preorder,int[] inorder) {
	
	if(preorder.length==0) {
		return null;
	}
	
	return buildTree(preorder,inorder,0,inorder.length-1);
	

}
public static TreeNode buildTree(int[] preorder, int[] inorder, int si, int ei) {
	
	if(si>ei) {
		return null;
	}
	int data=preorder[index];
	index++;
	
	TreeNode root=new TreeNode(data);
	int k=-1;
	for(int i=si;i<=ei;i++) {
		if(inorder[i]==data) {
			k=i;
			break;
		}
	}
	
	root.right=buildTree(preorder,inorder,k+1,ei);
	root.left=buildTree(preorder,inorder,si,k-1);
	return root;
}

private static void display(TreeNode node) {
	String str = "";
	if (node.left != null) {
		str = str + node.left.val + " => ";
	} else {
		str = str + "END => ";
	}
	str = str + node.val;

	if (node.right != null) {
		str = str + " => " + node.right.val;
	} else {
		str = str + " <= END";
	}
	System.out.println(str);

	if (node.left != null) {
		display(node.left);
	}
	if (node.right != null) {
		display(node.right);
	}

}

}

Your index variable is incrementing indefinitely causing to access an improbable index.

can you tell me how to fix this

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.