the way you told me to construct bst i m doing so but still getting wrong answer
Still showing wrong answer
@shudhanshu20092001_af6f20d24c617008 Sorry to say but this question requires a little out of the box approach. You don’t need to construct a BST instead consider that you have a empty BST(No nodes) and add the nodes using AddNode function of BST and the adding of nodes will be in the same order as they are given in the input : (Look for EACH AND EVERY COMMENT OTHERWISE YOU WILL NOT GET THE CODE) Fully Corrected code :
import java.util.*;
public class Main{
public static void main(String args[]) {
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 min=sc.nextInt();
int max=sc.nextInt();
BST treeroot=new BST();//BST constructor without Array is called
//Adding nodes individually at a time
for(int i=0;i<n;i++)
{
treeroot.addNode(arr[i]);
}
System.out.print("# Preorder : ");
treeroot.preorder();
System.out.println();
System.out.print("# Nodes within range are : ");
treeroot.inorder(min,max);
System.out.println();
}
}
}
class BST
{
private class Node {
int data;
Node left;
Node right;
//Constructor with data as argument
Node(int data){
this.data = data;
}
//Constructor with empty argument
Node(){
}
}
private Node root;
public BST()
{
this.root = null;
}
public BST(int[] arr)
{
this.root=construct(arr,0,arr.length-1);
}
private Node construct(int [] arr,int lo,int hi)
{
if(lo>hi){
return null;
}
int mid=(lo+hi)/2;
Node nn=new Node();
nn.data=arr[mid];
nn.left=construct(arr,lo,mid-1);
nn.right=construct(arr,mid+1,hi);
return nn;
}
//Function for adding Node
void addNode(int data)
{
this.root = insertRec(this.root, data);
}
Node insertRec(Node root, int data)
{
/* If the tree is empty,
return a new node */
if (root == null) {
root = new Node(data);
return root;
}
/* Otherwise, recur down the tree */
else if (data < root.data)
root.left = insertRec(root.left, data);
else if (data > root.data)
root.right = insertRec(root.right, data);
/* return the (unchanged) node pointer */
return root;
}
public void preorder()
{
this.preorder(this.root);
}
private void preorder(Node node)
{
if(node==null)
return;
System.out.print(node.data+" ");
preorder(node.left);
preorder(node.right);
}
// public void replaceWithLargerNodesSum() {
// // Write your code here
// replaceWithLargerNodesSum(this.root,0);
// }
// private int replaceWithLargerNodesSum(Node root, int sum)
// {
// //Base Case
// if(root == null)
// return sum;
// //Recursive Case
// sum = replaceWithLargerNodesSum(root.right,sum);
// sum += root.data;
// root.data = sum;
// return replaceWithLargerNodesSum(root.left,sum);
// }
public void inorder( int min,int max)
{
inorder(this.root,min,max);
}
private void inorder(Node node,int min,int max)
{ if(node==null)
return;
inorder(node.left,min,max);if(node.data<=max && node.data>=min)
System.out.print(node.data+" ");
inorder(node.right,min,max);
}
}