import java.util.*;
public class Main {
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
Main m = new Main();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] pre = new int[n];
for(int i=0;i<n;i++){
pre[i] = sc.nextInt();
}
int[] in = new int[n];
for(int i=0;i<n;i++){
in[i] = sc.nextInt();
}
BinaryTree bt = m.new BinaryTree(pre, in);
// int largestBst = bt.largestBST();
}
private class BinaryTree {
private class Node {
int data;
Node left;
Node right;
Node(int data){
this.data = data;
}
}
private Node root;
private int size;
public BinaryTree(int[] pre, int[] in) {
this.root = this.construct(in,pre,0,in.length-1,0,pre.length-1);
}
private Node construct( int[] in,int[] pre,int inS,int inE,int preS,int preE) {
if(inS>inE){
return null;
}
int rootData = pre[preS];
int rootIndex = -1;
for(int i =inS;i<=inE;i++){
if(in[i] == rootData){
rootIndex = i;
break;
}
}
int lpreS = preS+1;
int linS = inS;
int linE = rootIndex-1;
int lpreE = linE - linS + lpreS;
int rpreS = lpreS+1;
int rpreE = preE;
int rinS = rootIndex+1;
int rinE = inE;
Node nn = new Node(rootData);
nn.left = construct(in,pre,linS,linE,lpreS,lpreE);
nn.right = construct(in,pre,rinS,rinE,rpreS,rpreE);
return nn;
}
}}
//sir I’m using this code to create the tree but it is showing index out of bounds exception.
But, when I was using this for the problem construct tree from preorder and inorder traversal, it worked absolutely fine .