What is wrong in my code?

import java.util.Scanner;

public class printallnodesatkdistance {

public static void main(String[] args) {
	Scanner scn = new Scanner(System.in);
	int n = scn.nextInt();
	int[] preorder = new int[n];
	int[] inorder = new int[n];
	for (int i = 0; i < n; i++) {
		preorder[i] = scn.nextInt();
	}
	for (int j = 0; j < n; j++) {
		inorder[j] = scn.nextInt();
	}
	int t = scn.nextInt();
	for (int a = 0; a <t; a++) {
		int data = scn.nextInt();
		int k = scn.nextInt();
		printnodesatkdistance(inorder, data, k);
		
	}

}

private static void printnodesatkdistance(int[] inorder, int data, int k) {

	for (int i=0;i<inorder.length;i++) {
		System.out.println(inorder[i]);
	}
	
	
	int idx=binarysearch(inorder,data); 
	
	System.out.print(inorder[idx - k] + " ");
	System.out.print(inorder[idx + k]);

}

public static int binarysearch(int [] arr, int item) {
	 
	int lo=0;
	int hi=arr.length-1;
	while (lo<=hi) {
		int mid=(lo+hi)/2;
		if (arr[mid]<item) {
			lo=mid+1;
		}
		else if (arr[mid]>item) {
			hi=mid-1;
			
		}
		else {
			return mid;
		}
	}
	return -1;
}

}

you are getting ArrayIndexOutOfBoundsException error fror your inorder[idx - k] where you try to access inorder[-2] that doesnt exist.

For this problem we can encounter two kinds of nodes .

  • Nodes in the subtree rooted with target node.
  • Other nodes, may be an ancestor of target, or a node in some other subtree.

Finding the first type of nodes is easy to implement. Just traverse subtrees rooted with the target node and decrement k in recursive call. When the k becomes 0, print the node currently being traversed .
For the output nodes not lying in the subtree with the target node as the root, we must go through all ancestors. For every ancestor, we find its distance from target node, let the distance be d, now we go to other subtree (if target was found in left subtree, then we go to right subtree and vice versa) of the ancestor and find all nodes at k-d distance from the ancestor.

you can refer to this approach if you need