public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        TreeNode<Integer> root = TestSwapTree.createTreeNode(1);
        Map<Integer, TreeNode<Integer>> treeNodes = new HashMap<>();

        treeNodes.put(1, root);
        for (int i = 1; i <= n; ++i) {
            TreeNode<Integer> parent = treeNodes.get(i);
            int left = in.nextInt();
            int right = in.nextInt();
            TreeNode<Integer> leftNode = null;
            TreeNode<Integer> rightNode = null;
            if (left != -1) {
                leftNode = TestSwapTree.createTreeNode(left);
                treeNodes.put(left, leftNode);
            }
            if (right != -1) {
                rightNode = TestSwapTree.createTreeNode(right);
                treeNodes.put(right, rightNode);
            }
            parent.left = leftNode;
            parent.right = rightNode;
        }


        int t = in.nextInt();
        int levels[] = new int[t];
        for (int i = 0; i < t; ++i)
            levels[i] = in.nextInt();

        int height = TestSwapTree.getHeight(root);
        for (int level : levels) {
            for (int i=1; i < height; ++i) {
                int rLevel = level*i;
                if (rLevel > height)
                    break;
                List<TreeNode<Integer>> nodes = new ArrayList<>();
                TestSwapTree.getLevelNodes(root, 1, rLevel, nodes);

                for (TreeNode<Integer> node : nodes) {
                    swap(node);
                }
            }
            printInOrder(root);
            System.out.println();
        }
    }