import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
Main m=new Main();
int t=sc.nextInt();
while(t-->0){
int n1=sc.nextInt();
int a1[]=new int[n1];
for(int i=0;i<n1;i++){
a1[i]=sc.nextInt();
}
int k1=sc.nextInt();
int k2=sc.nextInt();
Arrays.sort(a1);
BST tree=m.new BST(a1);
tree.preorder();
System.out.println();
tree.inorder(k1,k2);
System.out.println();
}
}
class BST{
class Node{
Node left;
Node right;
int data;
}
Node root;
public BST(int a1[]){
this.root=this.construct(a1,0,a1.length-1);
}
public Node construct(int a1[], int lo, int hi){
if(lo>hi)
return null;
int mid=(lo+hi)/2;
Node nn=new Node();
nn.data=a1[mid];
nn.left=construct(a1,lo,mid-1);
nn.right=construct(a1,mid+1,hi);
return nn;
}
public void preorder(){
System.out.print("# Preorder : ");
this.preorder(this.root);
}
private void preorder(Node node){
if(node!=null){
System.out.print(node.data+" ");
preorder(node.left);
preorder(node.right);
}
}
public void inorder(int k1, int k2){
System.out.print("# Nodes within range are : ");
this.inorder(this.root, k1, k2);
}
private void inorder(Node node, int k1,int k2){
if(node!=null){
inorder(node.left,k1,k2);
if(node.data>=k1&&node.data<=k2){
System.out.print(node.data+" ");
}
inorder(node.right,k1,k2);
}
}
}
}
Whats wrong in my code?
The array given in the input is not the preorder traversal of the BST to be formed. It is just a random unsorted array and you need to create a BST from the given unsorted array.
https://ide.codingblocks.com/s/331100 I have attached the code of the input method of your reference. The code in the video was for sorted arrays
if given array unsorted array then can we sort the array then make BST??