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;
public Node(int data){
this.data = data;
left = right = null;
}
}
private Node root;
private int size;
HashMap<Integer, Integer> map = new HashMap<>();
public BinaryTree(int[] pre, int[] in) {
for(int i=0;i<in.length;i++){
map.put(in[i], i);
}
this.root = this.construct(pre, 0, map, in, 0, in.length - 1);
}
private Node construct(int[] pre, int plo, HashMap<Integer, Integer> map, int[] in, int ilo, int ihi) {
// write your code here
if(ilo > ihi)
return null;
int data = pre[plo++];
Node cur = new Node(data);
if(ilo == ihi)
return cur;
cur.left = construct(pre, plo, map, in, ilo, map.get(data)-1);
cur.right = construct(pre, plo, map, in, map.get(data)+1, ihi);
return cur;
}
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);
}
}
}
this code is passing only one test case … please help!!