import java.util.*;


public class Solution {
    private Map<Integer,Integer> indexs = new HashMap<>();
    private int i = 0;
    public int[] solve (int[] pre, int[] vin) {
        for(int i = 0; i < vin.length; i++){
            indexs.put(vin[i],i);
        }
        TreeNode root = helper(pre,vin,0,vin.length - 1);
        Queue<TreeNode> queue = new LinkedList<>();
        if(root == null) return null;
        int heigh = getHeigh(root);
        int[] ans = new int[heigh];
        int index = 0;
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            while(size-- != 0){
                TreeNode node = queue.poll();
                if(node.left != null) queue.offer(node.left);
                if(node.right != null) queue.offer(node.right);
                if(size == 0) ans[index++] = node.val;
            }
        }
        return ans;
    }
    
 
      // [left,right];
    private TreeNode helper(int[] pre,int[] vin,int left,int right){
        if(left > right) return null;
        TreeNode root = new TreeNode(pre[i]);
        int index_mid = indexs.get(pre[i]);
        i++;
        root.left = helper(pre,vin,left,index_mid-1);
        root.right = helper(pre,vin,index_mid+1,right);
        return root;
    }
    
    
    private int getHeigh(TreeNode root){
        return root == null ? 0 : 1 + Math.max(getHeigh(root.left),getHeigh(root.right));
    }
     
}