using System;
using System.Collections.Generic;
using System.IO;
class TreeNode
{
    public int data { get; set; }
    public TreeNode left { get; set; }
    public TreeNode right { get; set; }
    public TreeNode(int data)
    {
        this.data = data;
        left = null;
        right = null;
    }

}
class Solution {
    static void Main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */      int n = int.Parse(Console.ReadLine());
        Queue<TreeNode> q = new Queue<TreeNode>();
        TreeNode temp, lChild, rChild;

        TreeNode root = new TreeNode(1);
        q.Enqueue(root);

        for (int i = 0; i < n; i++)
        {
            temp = q.Dequeue();
            int[] children = Array.ConvertAll(Console.ReadLine().Split(' '),int.Parse);
            if (children[0] != -1)
            {
                lChild = new TreeNode(children[0]);
                temp.left = lChild;
                q.Enqueue(lChild);
            }
            if (children[1] != -1)
            {
                rChild= new TreeNode(children[1]);
                temp.right = rChild;
                q.Enqueue(rChild);
            }
        }
        int t = int.Parse(Console.ReadLine());
        for(int i = 0; i < t; i++)
        {
            int k= int.Parse(Console.ReadLine());
            int atHeight = 1;
            SwapNodes(root,k,atHeight);
            Inorder(root);
            Console.WriteLine();
        }
    }
    private static void SwapNodes(TreeNode root, int k, int atHeight)
    {
        if (root != null)
        {
            if (atHeight % k == 0)
            {
                TreeNode temp = root.left;
                root.left = root.right;
                root.right = temp;
            }
            SwapNodes(root.left, k, atHeight + 1);
            SwapNodes(root.right, k, atHeight + 1);
        }
    }
    private static void Inorder(TreeNode root)
    {
        if (root != null)
        {
            Inorder(root.left);
            Console.Write(root.data+" ");
            Inorder(root.right);
        }
    }
}