Code gives correct ans for the given test case but wrong answer for the only test case on submitting.
CODE:
import java.util.;
import java.io.;
public class Main {
public static void main(String args[]) throws IOException {
Main mainObj = new Main();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
int n = Integer.parseInt(br.readLine());
String str[] = br.readLine().trim().split("\\s+");
int arr[] = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(str[i]);
}
BST bst = mainObj.new BST(arr);
bst.preOrder();
}
class BST {
class Node {
int data;
Node left;
Node right;
}
private Node root;
public BST(int arr[]) {
this.root = constructBST(arr, 0, arr.length - 1);
}
public Node constructBST(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 = constructBST(arr, lo, mid - 1);
nn.right = constructBST(arr, mid + 1, hi);
return nn;
}
public void preOrder() {
this.preOrder(this.root);
}
private void preOrder(Node node) {
if(node == null) {
return;
}
System.out.print(node.data + " ");
this.preOrder(node.left);
this.preOrder(node.right);
}
}
}
I’ve tried this also while calculating mid:
import java.util.;
import java.io.;
public class Main {
public static void main(String args[]) throws IOException {
Main mainObj = new Main();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
int n = Integer.parseInt(br.readLine());
String str[] = br.readLine().trim().split("\\s+");
int arr[] = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(str[i]);
}
BST bst = mainObj.new BST(arr);
bst.preOrder();
}
class BST {
class Node {
int data;
Node left;
Node right;
}
private Node root;
public BST(int arr[]) {
this.root = constructBST(arr, 0, arr.length - 1);
}
public Node constructBST(int arr[], double lo, double hi) {
if(lo > hi) {
return null;
}
int mid = (int) Math.ceil((lo + hi) / 2);
Node nn = new Node();
nn.data = arr[mid];
nn.left = constructBST(arr, lo, mid - 1);
nn.right = constructBST(arr, mid + 1, hi);
return nn;
}
public void preOrder() {
this.preOrder(this.root);
}
private void preOrder(Node node) {
if(node == null) {
return;
}
System.out.print(node.data + " ");
this.preOrder(node.left);
this.preOrder(node.right);
}
}
}