Incorrect output in tree construction
import java.util.*;
public class Main {
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
Main m = new Main();
int[] pre = takeInput();
int[] in = takeInput();
BinaryTree bt = m.new BinaryTree(pre, in);
bt.display();
}
public static int[] takeInput() {
int n = scn.nextInt();
int[] rv = new int[n];
for (int i = 0; i < rv.length; i++) {
rv[i] = scn.nextInt();
}
return rv;
}
private class BinaryTree {
private class Node {
int data;
Node left;
Node right;
}
private Node root;
private int size;
public BinaryTree(int[] pre, int[] in) {
this.root = this.construct(pre, 0, pre.length - 1, in, 0, in.length - 1);
}
private Node construct(int[] pre, int plo, int phi, int[] in, int ilo, int ihi) {
if(ilo>ihi)
return null;
Node nn;//you have to create a new node instead of assigning a new node to root
nn=new Node();
nn.data=pre[plo];
int k=-1;
for(int i=ilo;i<=ihi;i++)
if(in[i]==pre[plo])
k=i;
nn.left=construct(pre,plo+1,plo+k-ilo,in,ilo,k-1);
nn.right=construct(pre,phi-ihi+k+1,phi,in,k+1,ihi);
return nn;
}
public void display() {
this.display(this.root);
}
private void display(Node node) {
if (node == null) {
return;
}
String str = "";
if (node.left != null) {
str += node.left.data;
} else {
str += "END";
}
str += " => " + node.data + " <= ";
if (node.right != null) {
str += node.right.data;
} else {
str += "END";
}
System.out.println(str);
this.display(node.left);
this.display(node.right);
}
}
}
Thank you so much sir:)