Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Reconstruction of a Tree

Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.

Input

In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.

In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.

In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.

Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.

Output

Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.

Constraints

$1 \leq n \leq 40$

Sample Input 1

5
1 2 3 4 5
3 2 4 1 5

Sample Output 1

3 4 2 5 1

Sample Input 2

4
1 2 3 4
1 2 3 4

Sample Output 2

4 3 2 1

Solution in Ruby (judge verdict: Accepted)

class Node
  def initialize(id)
    @id = id
    @left = nil 
    @right = nil
  end

  attr_accessor :id, :left, :right
end

def reconstruct_visit(node, index, lefts, rights)
  direct_left = compare_by_preorder(lefts)
  direct_right = compare_by_preorder(rights)
  if direct_left >= 0 then
    node.left = Node.new(direct_left)
    left_index = lefts.index(direct_left)
    reconstruct_visit(node.left, 
          direct_left,
          lefts[0...left_index], 
          lefts[left_index+1..-1])
  end
  if direct_right >= 0 then
    node.right = Node.new(direct_right)
    right_index = rights.index(direct_right)
    reconstruct_visit(node.right, 
          direct_right,
          rights[0...right_index], 
          rights[right_index+1..-1])
  end
end

def compare_by_preorder(array)
  return -1 if array.size == 0
  ordered_array = array.map do |item|
    [item, $preorder.index(item)]
  end
  ordered_array.sort! {|x, y| x[1] <=> y[1]}
  return ordered_array[0][0]
end

def postorder(node, array)
  if (node.left != nil) then
    postorder(node.left, array)
  end
  if (node.right != nil) then
    postorder(node.right, array)
  end
  array << node.id
end


n = gets.chomp.to_i
$preorder = gets.chomp.split.map(&:to_i)
$inorder = gets.chomp.split.map(&:to_i)

root_node = Node.new($preorder[0])
root_index = $inorder.index($preorder[0])
reconstruct_visit(root_node, 
      root_index, 
      $inorder[0...root_index], 
      $inorder[root_index+1..-1])

postorder_array = []
postorder(root_node, postorder_array)
puts postorder_array.join(' ')