WRONG PREORDER IS COMING my output [ # Preorder : 4 2 3 5 6 # Nodes within range are : 3 4 5] why?

import java.util.*;

class Node{
		int data;
		Node left;
		Node right;
	}

 class BST{

	public  Node insert(int[] arr,int lo ,int hi ){
		if(lo > hi){
			return null;
		}
		int mid = (lo + hi)/2;
		Node node = new Node();
		node.data = arr[mid];
		node.left = insert(arr, lo, mid-1);
		node.right = insert(arr, mid+1,hi); 
		
		return node;
	}
	public static void preorder(Node node){
		if(node == null){
			return;
		}
	   System.out.print(node.data +" ");
	   preorder(node.left);
	   preorder(node.right);
	}

}
public class Main {
public static void main(String args[]) {
	BST bst = new BST();
	Scanner sc = new Scanner(System.in);
	int t = sc.nextInt();
	while(t--!= 0){
	int n = sc.nextInt();
	int[] arr =new int[n];
	for(int i = 0; i< n; i++){
		arr[i] = sc.nextInt();
	}
	int k1 = sc.nextInt();
	int k2 = sc.nextInt();
    Arrays.sort(arr);
	
	Node nn = bst.insert(arr,0, n-1);
	System.out.print("# Preorder : ");
	bst.preorder(nn);
	System.out.println();
	System.out.print("# Nodes within range are : ");
	for(int i = 0; i< n; i++){
		if(arr[i] >= k1 && arr[i] <= k2)
		System.out.print(arr[i]+" ");
	}

	}


	

}

}

Hey @ayush_r18,

Your error might lie in the building of the tree.
You are expected to add 1 element at a time while constructing the tree.

Building of tree is right because I submitted the same code in previous question and it’s right

but what’s the problem if I will do like this

Yes, the tree that will be built will be a binary search tree if you use it using the sorting method, but the problem expects you to insert the nodes one by one . The BSTs created by the two methods will be structurally different thus they are giving a different Pre Order Traversal .

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.