A binary tree is a tree which is characterized by one of the following properties:

It can be empty (null).
It contains a root node only.
It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees.

In-order traversal is performed as

Traverse the left subtree.
Visit root.
Traverse the right subtree.

For this in-order traversal, start from the left child of the root node and keep exploring the left subtree until you reach a leaf.  When you reach a leaf, back up to its parent, check for a right child and visit it if there is one.  If there is not a child, you've explored its left and right subtrees fully. If there is a right child, traverse its left subtree then its right in the same manner.  Keep doing this until you have traversed the entire tree.  You will only store the values of a node as you visit when one of the following is true:

it is the first node visited, the first time visited 
it is a leaf, should only be visited once  
all of its subtrees have been explored, should only be visited once while this is true  
it is the root of the tree, the first time visited  

Swapping: Swapping subtrees of a node means that if initially node has left subtree L and right subtree R, then after swapping, the left subtree will be R and the right subtree, L.

For example, in the following tree, we swap children of node 1.

                                Depth
    1               1            [1]
   / \             / \
  2   3     ->    3   2          [2]
   \   \           \   \
    4   5           5   4        [3]

In-order traversal of left tree is 2 4 1 3 5 and of right tree is 3 5 1 2 4.

Swap operation: 

We define depth of a node as follows:

The root node is at depth 1.
If the depth of the parent node is d, then the depth of current node will be d+1.

Given a tree and an integer, k, in one operation, we need to swap the subtrees of all the nodes at each depth h, where h ∈ [k, 2k, 3k,...].  In other words, if h is a multiple of k, swap the left and right subtrees of that level.

You are given a tree of n nodes where nodes are indexed from [1..n] and it is rooted at 1. You have to perform t swap operations on it, and after each swap operation print the in-order traversal of the current state of the tree.

Function Description

Complete the swapNodes function in the editor below.  It should return a two-dimensional array where each element is an array of integers representing the node indices of an in-order traversal after a swap operation.

swapNodes has the following parameter(s): 

- indexes: an array of integers representing index values of each $node[i]$, beginning with $node[1]$, the first element, as the root. 

- queries: an array of integers, each representing a $\boldsymbol{\mbox{k}}$ value.

Input Format 

The first line contains n, number of nodes in the tree.   

Each of the next n lines contains two integers, a b, where a is the index of left child, and b is the index of right child of i^{th} node.   

Note: -1 is used to represent a null node.   

The next line contains an integer, t, the size of $queries$. 

Each of the next t lines contains an integer $\textit{queries}[i]$, each being a value $\boldsymbol{\mbox{k}}$.  

Output Format 

For each k, perform the swap operation and store the indices of your in-order traversal to your result array.  After all swap operations have been performed, return your result array for printing.  

Constraints  

$1\leq n\leq1024$    
$1\leq t\leq100$  
$1\leq k\leq n$  
Either $a=-1$ or $2<=a<=n$  
Either $b=-1$ or $2<=b<=n$  
The index of a non-null child will always be greater than that of its parent.  

Sample Input 0  

3
2 3
-1 -1
-1 -1
2
1
1

Sample Output 0  

3 1 2
2 1 3

Explanation 0

As nodes 2 and 3 have no children, swapping will not have any effect on them. We only have to swap the child nodes of the root node.

    1   [s]       1    [s]       1   
   / \      ->   / \        ->  / \  
  2   3 [s]     3   2  [s]     2   3

Note:  [s] indicates that a swap operation is done at this depth.

Sample Input 1  

5
2 3
-1 4
-1 5
-1 -1
-1 -1
1
2

Sample Output 1  

4 2 1 5 3

Explanation 1

Swapping child nodes of node 2 and 3 we get

    1                  1  
   / \                / \ 
  2   3   [s]  ->    2   3
   \   \            /   / 
    4   5          4   5  

Sample Input 2  

11
2 3
4 -1
5 -1
6 -1
7 8
-1 9
-1 -1
10 11
-1 -1
-1 -1
-1 -1
2
2
4

Sample Output 2  

2 9 6 4 1 3 7 5 11 8 10
2 6 9 4 1 3 7 5 10 8 11

Explanation 2  

Here we perform swap operations at the nodes whose depth is either 2 or 4 for $K=2$ and then at nodes whose depth is 4 for $K=4$.

         1                     1                          1             
        / \                   / \                        / \            
       /   \                 /   \                      /   \           
      2     3    [s]        2     3                    2     3          
     /      /                \     \                    \     \         
    /      /                  \     \                    \     \        
   4      5          ->        4     5          ->        4     5       
  /      / \                  /     / \                  /     / \      
 /      /   \                /     /   \                /     /   \     
6      7     8   [s]        6     7     8   [s]        6     7     8
 \          / \            /           / \              \         / \   
  \        /   \          /           /   \              \       /   \  
   9      10   11        9           11   10              9     10   11

Difficulty: MEDIUM

Solutions:
def inorder(T):
	stack = [1]
	result = []
	while stack:
		i = stack.pop()
		if i > 0:
			if T[i][1] > 0:
				stack.append(T[i][1])
			stack.append(-i)
			if T[i][0] > 0:
				stack.append(T[i][0])
		else:
			result.append(-i)
	return result

def swap(T, K):
	(toVisit, depth) = ([1], 1)
	while toVisit:
		if depth % K == 0:
			for i in toVisit:
				T[i] = (T[i][1], T[i][0])
		toVisit_ = []
		for i in toVisit:
			if T[i][0] > 0:
				toVisit_.append(T[i][0])
			if T[i][1] > 0:
				toVisit_.append(T[i][1])
		toVisit = toVisit_
		depth += 1
N = int(input())
T = [None] + [tuple((int(_) for _ in input().split())) for _ in range(N)]
N = int(input())
for _ in range(N):
	swap(T, int(input()))
	print(' '.join((str(_) for _ in inorder(T))))


import sys

class Node:

	def __init__(self, val):
		self.val = val
		self.left = None
		self.right = None
		self.depth = 1

	def setLeft(self, left):
		self.left = left

	def setRight(self, right):
		self.right = right

	def setDepth(self, depth):
		self.depth = depth

	def getDepth(self):
		return self.depth

	def swapNode(self):
		(self.left, self.right) = (self.right, self.left)

def Solution(root):
	if root.left is None and root.right is None:
		return str(root.val)
	elif root.left is None:
		return str(root.val) + ' ' + Solution(root.right)
	elif root.right is None:
		return Solution(root.left) + ' ' + str(root.val)
	else:
		return Solution(root.left) + ' ' + str(root.val) + ' ' + Solution(root.right)
sys.setrecursionlimit(1050)
n = int(input())
nodes = []
nodes.append(Node(1))
for i in range(n):
	temp = [int(x) for x in input().split(' ')]
	for j in range(2):
		if temp[j] is not -1:
			tempNode = Node(temp[j])
			tempNode.setDepth(nodes[i].getDepth() + 1)
			nodes.append(tempNode)
			if j is 0:
				nodes[i].setLeft(tempNode)
			else:
				nodes[i].setRight(tempNode)
k = int(input())
for i in range(k):
	a = int(input())
	for x in nodes:
		if x.getDepth() % a is 0:
			x.swapNode()
	answer = Solution(nodes[0])
	print(answer)


def printTree(tree):
	s = ''
	todo = [(1, True)]
	while todo:
		(i, pl) = todo.pop()
		(a, b) = tree[i]
		if pl:
			todo.append((i, False))
			if a != -1:
				todo.append((a, True))
		else:
			s += ' %d' % i
			if b != -1:
				todo.append((b, True))
	print(s[1:])

def swapNodes(tree, k):
	todo = [(1, 1)]
	while todo:
		(i, d) = todo.pop()
		(a, b) = tree[i]
		if d % k == 0:
			tree[i] = (b, a)
		if a != -1:
			todo.append((a, d + 1))
		if b != -1:
			todo.append((b, d + 1))
n = int(input())
nodes = [None]
for _ in range(n):
	(a, b) = map(int, input().split())
	nodes.append((a, b))
t = int(input())
for _ in range(t):
	k = int(input())
	swapNodes(nodes, k)
	printTree(nodes)


N = int(input())
L = [-1] * (N + 1)
R = [-1] * (N + 1)
for i in range(1, N + 1):
	(L[i], R[i]) = [int(k) for k in input().split()]
T = int(input())
for _ in range(T):
	K = int(input())
	visited = [False] * (N + 1)
	ordering = []
	Q = [(1, 1)]
	while len(Q) > 0:
		(v, d) = Q[-1]
		if not visited[v]:
			if d % K == 0:
				(L[v], R[v]) = (R[v], L[v])
			if L[v] >= 0:
				Q.append((L[v], d + 1))
			visited[v] = True
		else:
			Q.pop()
			ordering.append(v)
			if R[v] >= 0:
				Q.append((R[v], d + 1))
	print(' '.join(map(str, ordering)))


class BinaryTree:

	def __init__(self, value=None):
		self.value = value
		self.left = None
		self.right = None

	def __str__(self):
		s = bt.in_order_traversal(lambda node: '%s ' % node.value, '')
		return s.strip()

	def in_order_traversal(self, f, init):
		result = init
		q = []
		node = self
		while len(q) > 0 or node is not None:
			if node is not None:
				q.append(node)
				node = node.left
			else:
				node = q.pop()
				result += f(node)
				node = node.right
		return result

	def level_order_traversal(self, f, init):
		result = init
		q = [self]
		level = 0
		while len(q) > 0:
			new_q = []
			level += 1
			for node in q:
				result += f(level, node)
				if not node.left is None:
					new_q.append(node.left)
				if not node.right is None:
					new_q.append(node.right)
			q = new_q
		return result

	def swap_children(self, k):

		def swap(level, node):
			if level % k == 0:
				(node.left, node.right) = (node.right, node.left)
			return []
		self.level_order_traversal(swap, [])

	def read_from_input(self, n=None):
		q = [self]
		while len(q) > 0:
			new_q = []
			for node in q:
				if n is not None:
					if n <= 0:
						return
					n -= 1
				(left, right) = map(int, input().split())
				if left != -1:
					node.left = BinaryTree(left)
					new_q.append(node.left)
				if right != -1:
					node.right = BinaryTree(right)
					new_q.append(node.right)
			q = new_q
n = int(input())
bt = BinaryTree(1)
bt.read_from_input(n)
t = int(input())
while t > 0:
	k = int(input())
	bt.swap_children(k)
	print(bt)
	t -= 1


from collections import deque

class Node:

	def __init__(self, num):
		self.num = num
		self.leftChild = None
		self.rightChild = None

	def __repr__(self):
		left_child_num = -1 if self.leftChild is None else self.leftChild.num
		right_child_num = -1 if self.rightChild is None else self.rightChild.num
		return str(self.num) + '(' + str(left_child_num) + ' , ' + str(right_child_num) + ')'

	def setLeftChild(self, leftChild):
		self.leftChild = leftChild

	def setRightChild(self, rightChild):
		self.rightChild = rightChild

	def __hash__(self):
		return hash(self.num)

	def __eq__(self, other):
		return self.num == other.num

def getHeight_iter(root_node):
	node_queue = deque()
	level_to_nodes_dict = dict()
	node_queue.append(root_node)
	height = 0
	while True:
		count = len(node_queue)
		if len(node_queue) == 0:
			return (height, level_to_nodes_dict)
		height += 1
		while count > 0:
			top_node = node_queue.popleft()
			if height in level_to_nodes_dict:
				level_to_nodes_dict[height].append(top_node)
			else:
				level_to_nodes_dict[height] = [top_node]
			count -= 1
			if top_node.leftChild is not None:
				node_queue.append(top_node.leftChild)
			if top_node.rightChild is not None:
				node_queue.append(top_node.rightChild)

def swap(nodes):
	for n in nodes:
		temp_child = n.leftChild
		n.leftChild = n.rightChild
		n.rightChild = temp_child

def inorder_traverse_iter(root_node, order):
	stack = []
	current = root_node
	while True:
		while current is not None:
			stack.append(current)
			current = current.leftChild
		if not stack:
			return
		current = stack.pop()
		order.append(str(current.num))
		while current.rightChild is None and stack:
			current = stack.pop()
			order.append(str(current.num))
		current = current.rightChild
nodes = int(input())
root_node = None
nodes_dict = dict()
for i in range(0, nodes):
	j = i + 1
	node = Node(j)
	if node in nodes_dict:
		node = nodes_dict[node]
	else:
		nodes_dict[node] = node
	(left_num, right_num) = input().split()
	(left_num, right_num) = (int(left_num), int(right_num))
	if left_num >= 2:
		left_child = Node(left_num)
		if left_child in nodes_dict:
			node = nodes_dict[left_child]
		else:
			nodes_dict[left_child] = left_child
		node.setLeftChild(left_child)
	if right_num >= 2:
		right_child = Node(right_num)
		if right_child in nodes_dict:
			node = nodes_dict[right_child]
		else:
			nodes_dict[right_child] = right_child
		node.setRightChild(right_child)
	if i == 0:
		root_node = node
(height, level_to_nodes_dict) = getHeight_iter(root_node)
T = int(input())
for i in range(0, T):
	depth_index = int(input())
	result = []
	increment_fac = depth_index
	while depth_index <= height:
		nodes_at_level = level_to_nodes_dict[depth_index]
		swap(nodes_at_level)
		depth_index += increment_fac
	order = []
	inorder_traverse_iter(root_node, order)
	string = ' '.join(order)
	print(string)


N = int(input())
tree = [[int(ch) for ch in input().split()] for i in range(N)]
levels = [True] * N

def traverse():
	stack = []
	stack.append((1, 0, 0))
	traversal = []
	while len(stack) > 0:
		(node, level, state) = stack.pop()
		if state == 0:
			stack.append((node, level, 1))
			L = tree[node - 1][0] if levels[level] else tree[node - 1][1]
			if L != -1:
				stack.append((L, level + 1, 0))
		elif state == 1:
			stack.append((node, level, 2))
			traversal.append(node)
		elif state == 2:
			stack.append((node, level, 3))
			R = tree[node - 1][1] if levels[level] else tree[node - 1][0]
			if R != -1:
				stack.append((R, level + 1, 0))
		elif state == 4:
			pass
	print(' '.join((str(i) for i in traversal)))
T = int(input())
for Ti in range(T):
	K = int(input())
	Ki = K
	while Ki <= N:
		levels[Ki - 1] = not levels[Ki - 1]
		Ki += K
	traverse()


import sys
sys.setrecursionlimit(10000)

def parse(n):
	tree = dict()
	for i in range(1, n + 1):
		tree[i] = tuple(map(int, input().split()))
	return tree

def inorder(tree, root):
	if root == -1:
		return []
	(left, right) = tree[root]
	return inorder(tree, left) + [root] + inorder(tree, right)

def doswap(tree, root, swaplvl):
	currnodes = [root]
	currlvl = 1
	while currnodes:
		if currlvl % swaplvl == 0:
			for node in currnodes:
				(l, r) = tree[node]
				tree[node] = (r, l)
		nextnodes = []
		for node in currnodes:
			(l, r) = tree[node]
			if l != -1:
				nextnodes.append(l)
			if r != -1:
				nextnodes.append(r)
		currnodes = nextnodes
		currlvl += 1
n = int(input())
tree = parse(n)
t = int(input())
for i in range(t):
	doswap(tree, 1, int(input()))
	print(' '.join(map(str, inorder(tree, 1))))


import math
import sys
sys.setrecursionlimit(15000)

class Node:

	def __init__(self, value, left, right):
		self.value = value
		self.left = left
		self.right = right

def main():
	n = int(input())
	nodes = [Node(i, None, None) for i in range(1, n + 1)]
	for i in range(n):
		[left, right] = [int(value) for value in input().split()]
		if left != -1:
			nodes[i].left = nodes[left - 1]
		if right != -1:
			nodes[i].right = nodes[right - 1]
	height = getHeight(nodes[0])
	for _ in range(int(input())):
		levelIncrement = int(input())
		for level in range(levelIncrement, height, levelIncrement):
			nodesToSwap = nodesAtLevel(nodes[0], level)
			for node in nodesToSwap:
				if node != None:
					(node.left, node.right) = (node.right, node.left)
		printStack = inorderTraversal(nodes[0])
		print(' '.join([str(value) for value in printStack]))

def getHeight(root):
	if root != None:
		return max([1 + getHeight(root.left), 1 + getHeight(root.right)])
	return 0

def nodesAtLevel(root, level):
	nodes = []
	nodes.append(root)
	numNodesAtCurrentLevel = 1
	numNodesAtNextLevel = 0
	currentLevel = 1
	if currentLevel == level:
		return nodes
	while nodes:
		node = nodes[0]
		del nodes[0]
		numNodesAtCurrentLevel -= 1
		if node.left != None:
			nodes.append(node.left)
			numNodesAtNextLevel += 1
		if node.right != None:
			nodes.append(node.right)
			numNodesAtNextLevel += 1
		if numNodesAtCurrentLevel == 0:
			currentLevel += 1
			if currentLevel == level:
				return nodes
			numNodesAtCurrentLevel = numNodesAtNextLevel
			numNodesAtNextLevel = 0
	return nodes

def inorderTraversal(root):
	if root == None:
		return
	nodes = []
	printStack = []
	done = False
	current = root
	while not done:
		if current != None:
			nodes.append(current)
			current = current.left
		elif nodes:
			current = nodes.pop()
			printStack.append(current.value)
			current = current.right
		else:
			done = True
	return printStack
main()


def print_inorder(nodes):
	to_print = []
	stack = [(1, False)]
	while len(stack) != 0:
		elem = stack.pop()
		node_i = elem[0]
		if elem[1]:
			to_print.append(node_i)
			continue
		left = nodes[node_i]['left']
		right = nodes[node_i]['right']
		if right != -1:
			stack.append((right, False))
		stack.append((node_i, True))
		if left != -1:
			stack.append((left, False))
	print(' '.join((str(i) for i in to_print)))
N = int(input())
nodes = {}
for i in range(1, N + 1):
	(left, right) = [int(i) for i in input().split()]
	nodes[i] = {'left': left, 'right': right}
swaps = {}
node_by_depth = {1: [1]}
queue = [(1, 1)]
while len(queue) != 0:
	elem = queue.pop(0)
	node_index = elem[0]
	left = nodes[node_index]['left']
	right = nodes[node_index]['right']
	depth = elem[1]
	new_depth = depth + 1
	if new_depth not in node_by_depth:
		node_by_depth[new_depth] = []
	if left != -1:
		queue.append((left, depth + 1))
		node_by_depth[new_depth].append(left)
	if right != -1:
		queue.append((right, depth + 1))
		node_by_depth[new_depth].append(right)
	count = 0
	for K in swaps.keys():
		if depth % K == 0:
			count += 1
	if count % 2 == 1:
		nodes[nodex_index] = {'left': right, 'right': left}
T = int(input())
for t in range(T):
	K = int(input())
	for depth in node_by_depth.keys():
		if depth % K == 0:
			for node_i in node_by_depth[depth]:
				node = nodes[node_i]
				nodes[node_i] = {'left': node['right'], 'right': node['left']}
	print_inorder(nodes)


import sys
sys.setrecursionlimit(15000)
d = [0] * 2048
l = [0] * 2048
r = [0] * 2048
res = []

def w_tree(current):
	if l[current] > 0:
		w_tree(l[current])
	if current != 0:
		res.append(current)
	else:
		res.append(1)
	if r[current] > 0:
		w_tree(r[current])

def calc_dep(current, depth):
	d[current] = depth
	if l[current] > 0:
		calc_dep(l[current], depth + 1)
	if r[current] > 0:
		calc_dep(r[current], depth + 1)

def print_tree():
	s = ' '.join([str(c) for c in res])
	print(s)

def inverse():
	n = int(input())
	for i in range(1, n + 1):
		(l[i], r[i]) = list(map(int, input().split()))
	calc_dep(1, 1)
	for z in range(int(input())):
		k = int(input())
		for i in range(1, n + 1):
			if d[i] % k == 0:
				(l[i], r[i]) = (r[i], l[i])
		w_tree(1)
		print_tree()
		res.clear()
inverse()


import sys

class Node(object):

	def __init__(self, data=None, left_node=None, right_node=None):
		self.data = data
		self.left = left_node
		self.right = right_node

	def __str__(self):
		return '<Node {} {} {}>'.format(self.left, self.data, self.right)

def Inorder(root):
	if not root:
		return []
	return Inorder(root.left) + [str(root.data)] + Inorder(root.right)

def swap_nodes(root, k, d=1):
	if not root:
		return
	if not d % k:
		(root.left, root.right) = (root.right, root.left)
	swap_nodes(root.left, k, d + 1)
	swap_nodes(root.right, k, d + 1)
n_nodes = int(input())
node = [Node(i) for i in range(n_nodes + 1)]
for i in range(1, n_nodes + 1):
	(l, r) = map(int, input().split())
	if l > 0:
		node[i].left = node[l]
	if r > 0:
		node[i].right = node[r]
sys.setrecursionlimit(8000)
n_tests = int(input())
for t in range(n_tests):
	k = int(input())
	swap_nodes(node[1], k)
	print(' '.join(Inorder(node[1])))


from collections import defaultdict, deque

class BinaryNode(object):

	def __init__(self, value, left, right):
		self.value = value
		self.left = left
		self.right = right

class BinaryTree(object):

	def __init__(self, root):
		self.root = root
		self.depths = self.compute_depths(self.root)

	@classmethod
	def from_input(cls):
		nodes = [None] * int(input())
		for i in range(len(nodes)):
			(left, right) = map(int, input().split())
			nodes[i] = BinaryNode(i + 1, left if left > 0 else None, right if right > 0 else None)
		for node in nodes:
			if node.left is not None:
				node.left = nodes[node.left - 1]
			if node.right is not None:
				node.right = nodes[node.right - 1]
		return cls(nodes[0] if nodes else None)

	def compute_depths(self, root):
		depths = defaultdict(set)
		queue = []
		if root is not None:
			queue.append((root, 1))
		while queue:
			(node, depth) = queue.pop()
			depths[depth].add(node)
			if node.left is not None:
				queue.append((node.left, depth + 1))
			if node.right is not None:
				queue.append((node.right, depth + 1))
		return depths

	def swap_K(self, K):
		for depth in range(K, len(self.depths) + 1, K):
			self.swap_depth(depth)

	def swap_depth(self, depth):
		for node in self.depths[depth]:
			self.swap_node(node)

	def swap_node(self, node):
		(node.left, node.right) = (node.right, node.left)

	def __repr__(self):
		if self.root is None:
			return ''
		result = []
		order = deque([self.root])
		while order:
			node = order.pop()
			if isinstance(node, int):
				result.append(node)
			else:
				if node.right is not None:
					order.append(node.right)
				order.append(node.value)
				if node.left is not None:
					order.append(node.left)
		return ' '.join(map(str, result))
tree = BinaryTree.from_input()
T = int(input())
for _ in range(T):
	K = int(input())
	tree.swap_K(K)
	print(tree)


import sys
sys.setrecursionlimit(15000)
nodes = []

def inorder(i, nodes):
	results = []
	left = nodes[i][0]
	right = nodes[i][1]
	if left != -1:
		results.extend(inorder(left - 1, nodes))
	results.append(i + 1)
	if right != -1:
		results.extend(inorder(right - 1, nodes))
	return results

def goto_depth(i, k):
	results = []
	left = nodes[i][0]
	right = nodes[i][1]
	if k == 1:
		if left == -1 and right == -1:
			return []
		return [i]
	if left != -1:
		results.extend(goto_depth(left - 1, k - 1))
	if right != -1:
		results.extend(goto_depth(right - 1, k - 1))
	return results

def swap(i, nodes):
	nodes[i].reverse()

def pp(arr):
	print(' '.join([str(i) for i in arr]))
max_depth = 0
N = int(input())
for i in range(0, N):
	nodes.append([int(i) for i in input().split(' ')])
	left = nodes[i][0]
	right = nodes[i][1]
	if left != -1 or right != -1:
		max_depth += 1
T = int(input())
for i in range(T):
	K = int(input())
	k = K
	while k < max_depth + 2:
		swap_list = goto_depth(0, k)
		for idx in swap_list:
			swap(idx, nodes)
		k += K
	pp(inorder(0, nodes))


import sys
sys.setrecursionlimit(15000)

def inorder(nodes, i):
	result = []
	if i != -1:
		result += inorder(nodes, nodes[i][0])
		result.append(str(i))
		result += inorder(nodes, nodes[i][1])
	return result

def get_depth_nodes(nodes, depth):
	if depth < 1:
		return []
	elif depth == 1:
		return [1]
	results = []
	for i in get_depth_nodes(nodes, depth - 1):
		results += [j for j in nodes[i] if j != -1]
	return results

def swap(nodes, k):
	depth = k
	nodes_at_depth = get_depth_nodes(nodes, depth)
	while nodes_at_depth:
		for i in nodes_at_depth:
			(nodes[i][0], nodes[i][1]) = (nodes[i][1], nodes[i][0])
		depth += k
		nodes_at_depth = get_depth_nodes(nodes, depth)
n = int(input().strip())
nodes = [[1]]
for i in range(n):
	nodes.append([int(i) for i in input().strip().split()])
t = int(input().strip())
for i in range(t):
	k = int(input().strip())
	swap(nodes, k)
	result = inorder(nodes, 1)
	print(' '.join(result))


import sys
sys.setrecursionlimit(15000)

class Node:

	def __init__(self, data, depth=1, left=None, right=None):
		self.data = data
		self.left = left
		self.right = right
		self.depth = depth

def inOrderTraversal(head):
	if head:
		inOrderTraversal(head.left)
		traversal.append(head.data)
		inOrderTraversal(head.right)

def getDepthNodes(head, k):
	if head:
		getDepthNodes(head.left, k)
		if head.depth == k:
			depthNodes.append(head)
		getDepthNodes(head.right, k)
head = Node(1)
q = [head]
maxDepth = 0
for i in range(int(input())):
	(a, b) = map(int, input().split())
	current = q.pop(0)
	if a != -1:
		current.left = Node(a, current.depth + 1)
		maxDepth = current.depth + 1
		q.append(current.left)
	if b != -1:
		current.right = Node(b, current.depth + 1)
		maxDepth = current.depth + 1
		q.append(current.right)
for _ in range(int(input())):
	traversal = []
	depth = int(input())
	for d in range(depth, maxDepth, depth):
		depthNodes = []
		getDepthNodes(head, d)
		for node in depthNodes:
			(node.left, node.right) = (node.right, node.left)
	inOrderTraversal(head)
	print(' '.join([str(x) for x in traversal]))


from collections import deque
N = int(input())
TREE = [None]

def swap_nodes(root_idx, k):
	queue = deque([(root_idx, 1)])
	while queue:
		(idx, depth) = queue.popleft()
		(l, r) = TREE[idx]
		if depth % k == 0:
			TREE[idx] = (r, l)
		if l != -1:
			queue.append((l, depth + 1))
		if r != -1:
			queue.append((r, depth + 1))

def inorder(root_idx):
	stack = []
	stack.append((root_idx, False))
	while stack:
		(c, expanded) = stack.pop()
		if expanded:
			yield c
			continue
		(l, r) = TREE[c]
		if r != -1:
			stack.append((r, False))
		if l != -1:
			stack.append((c, True))
			stack.append((l, False))
		else:
			yield c
for _ in range(N):
	(l, r) = [int(i) for i in input().split(' ', 1)]
	TREE.append((l, r))
T = int(input())
for _ in range(T):
	K = int(input())
	swap_nodes(1, K)
	print(' '.join((str(i) for i in inorder(1))))


def inOrder(l):
	n = l[0]
	s = []
	r = []
	while s or n != -1:
		if n != -1:
			s.append(n)
			n = l[2 * n - 1]
		else:
			n = s.pop()
			r.append(n)
			n = l[2 * n]
	print(' '.join(map(str, r)))

def swapTree(l, k):
	h = 1
	i = 1
	while i < len(l):
		if (d[i] - 1) % k == 0:
			(l[i], l[i + 1]) = (l[i + 1], l[i])
			i += 2
		else:
			i += 1
	inOrder(l)
n = int(input())
l = [1]
d = [-1] * len(l)
d[0] = 1
for i in range(1, n + 1):
	l.extend(map(int, input().split()))
	d.extend([d[l.index(i)] + 1] * 2)
t = int(input())
for i in range(t):
	k = int(input())
	swapTree(l, k)


import sys
sys.setrecursionlimit(15000)

def swapDepth(nodes, root, depth, k):
	if root is None or root == -1:
		return
	(l, r) = nodes[root - 1]
	if depth % k == 0:
		nodes[root - 1] = (r, l)
	swapDepth(nodes, l, depth + 1, k)
	swapDepth(nodes, r, depth + 1, k)

def inOrder(root, nodes):
	if root == -1:
		return None
	(l, r) = nodes[root - 1]
	return ' '.join([str(i) for i in [inOrder(l, nodes), root, inOrder(r, nodes)] if i])
N = int(input().strip())
nodes = []
for i in range(N):
	(l, r) = input().strip().split(' ')
	nodes.append((int(l), int(r)))
T = int(input().strip())
for _ in range(T):
	swapDepth(nodes, 1, 1, int(input().strip()))
	print(inOrder(1, nodes))


import sys
sys.setrecursionlimit(15000)

def inorder(start=1):
	if start == -1:
		return
	inorder(left[start - 1])
	s.append(start)
	inorder(right[start - 1])

def get_depths(n=1, d=1):
	if n == -1:
		return
	depth[n - 1] = d
	d += 1
	get_depths(left[n - 1], d)
	get_depths(right[n - 1], d)
left = []
right = []
N = int(input())
for n in range(N):
	(a, b) = [int(x) for x in input().split()]
	left.append(a)
	right.append(b)
depth = [1] * N
get_depths()
T = int(input())
for t in range(T):
	s = []
	K = int(input())
	for (i, d) in enumerate(depth):
		if d % K == 0:
			(left[i], right[i]) = (right[i], left[i])
	inorder()
	print(' '.join(map(str, s)))


import queue
N = int(input())
Nodes = []
for i in range(N):
	Nodes.append([int(x) - 1 for x in input().split()] + [0])
q = queue.Queue()
q.put(0)
Nodes[0][2] = 1
while not q.empty():
	i = q.get()
	deg = Nodes[i][2]
	if Nodes[i][0] != -2:
		Nodes[Nodes[i][0]][2] = deg + 1
		q.put(Nodes[i][0])
	if Nodes[i][1] != -2:
		Nodes[Nodes[i][1]][2] = deg + 1
		q.put(Nodes[i][1])
T = int(input())
for _ in range(T):
	k = int(input())
	for i in range(N):
		if Nodes[i][2] % k == 0:
			temp = Nodes[i][0]
			Nodes[i][0] = Nodes[i][1]
			Nodes[i][1] = temp
	list = []
	s = queue.LifoQueue()
	current = 0
	while current != -2:
		s.put(current)
		current = Nodes[current][0]
	while not s.empty():
		i = s.get()
		list.append(i + 1)
		current = Nodes[i][1]
		while current != -2:
			s.put(current)
			current = Nodes[current][0]
	print(' '.join(map(str, list)))


from queue import Queue

class Node(object):

	def __init__(self, data=None, left=None, right=None):
		self.data = data
		self.left = left
		self.right = right

def swap(node):
	left = node.left
	node.left = node.right
	node.right = left

def add_children(node, children, node_queue):
	left = children[0]
	right = children[1]
	if left != -1:
		left_node = Node(left)
		node.left = left_node
		node_queue.put(left_node)
	if right != -1:
		right_node = Node(right)
		node.right = right_node
		node_queue.put(right_node)

def _inorder(root):
	node_stack = []
	order = []
	curr_node = root
	while node_stack or curr_node:
		if curr_node:
			node_stack.append(curr_node)
			curr_node = curr_node.left
		else:
			curr_node = node_stack.pop()
			order.append(curr_node.data)
			curr_node = curr_node.right
	return order

def inorder_traversal(root):
	order = _inorder(root)
	print(' '.join([str(i) for i in order]))

def swap_nodes(root, depth):
	curr_depth = 1
	nodes_at_curr_depth = []
	nodes_at_curr_depth.append(root)
	while nodes_at_curr_depth:
		nodes_at_next_depth = []
		for n in nodes_at_curr_depth:
			if curr_depth % depth == 0:
				swap(n)
			if n.left:
				nodes_at_next_depth.append(n.left)
			if n.right:
				nodes_at_next_depth.append(n.right)
		nodes_at_curr_depth = nodes_at_next_depth
		curr_depth += 1
num_nodes = int(input().strip())
root = Node(1)
node_queue = Queue()
node_queue.put(root)
for i in range(num_nodes):
	curr_node = node_queue.get()
	children = [int(i) for i in input().strip().split(' ')]
	add_children(curr_node, children, node_queue)
num_swaps = int(input().strip())
for i in range(num_swaps):
	depth = int(input().strip())
	swap_nodes(root, depth)
	inorder_traversal(root)


import sys

class TreeNode:

	def __init__(self, data=1, left=None, right=None):
		self.data = data
		self.left = left
		self.right = right

	def swapNode(self, k, i=1):
		if i % k == 0:
			(self.left, self.right) = (self.right, self.left)
		if self.left is not None:
			self.left.swapNode(k, i + 1)
		if self.right is not None:
			self.right.swapNode(k, i + 1)

	def toList(self):
		lstr = [str(self.data)]
		if self.left is not None:
			lstr = self.left.toList() + lstr
		if self.right is not None:
			lstr = lstr + self.right.toList()
		return lstr

def buildTree(arrIdx, i=1):
	if i == -1:
		return None
	return TreeNode(i, buildTree(arrIdx, arrIdx[i - 1][0]), buildTree(arrIdx, arrIdx[i - 1][1]))

def main():
	sys.setrecursionlimit(15000)
	n = int(input())
	arrIdx = [None] * n
	for i in range(n):
		(l, r) = input().split()
		(l, r) = (int(l), int(r))
		arrIdx[i] = (l, r)
	tree = buildTree(arrIdx)
	t = int(input())
	for i in range(t):
		k = int(input())
		tree.swapNode(k)
		print(' '.join(tree.toList()))
	return 0
exit(main())


import sys
sys.setrecursionlimit(1500)

def inorder(n, nodes):
	(left, right) = nodes[n]
	r = []
	if left != -1:
		r.append(inorder(left, nodes))
	r.append(str(n))
	if right != -1:
		r.append(inorder(right, nodes))
	return ' '.join(r)

def swap(k, n, d, nodes):
	if d % k == 0:
		temp = nodes[n][0]
		nodes[n][0] = nodes[n][1]
		nodes[n][1] = temp
	(left, right) = nodes[n]
	if left != -1:
		swap(k, left, d + 1, nodes)
	if right != -1:
		swap(k, right, d + 1, nodes)
n = int(input())
nodes = {}
for i in range(n):
	(left, right) = map(int, input().split())
	nodes[i + 1] = [left, right]
t = int(input())
for _ in range(t):
	k = int(input())
	swap(k, 1, 1, nodes)
	print(inorder(1, nodes))


class Node:

	def __init__(self, data, left=None, right=None):
		self.data = data
		self.left = left
		self.right = right

	def __str__(self):
		return 'Node(%s)' % self.data

def read_nodes():
	root = Node(1)
	q = [root]

	def read_node(n):
		if n != -1:
			node = Node(n)
			q.append(node)
			return node
	while len(q) > 0:
		(node, *q) = q
		(l, r) = map(int, input().split(' '))
		node.left = read_node(l)
		node.right = read_node(r)
	return root

def swap_level(root, top_lvl):
	st = [[root, top_lvl, 1]]
	while len(st) > 0:
		(node, lvl, cur_lvl) = st.pop()
		next_lvl = lvl
		if lvl == cur_lvl:
			l = node.left
			node.left = node.right
			node.right = l
			next_lvl += top_lvl
		if node.left:
			st.append([node.left, next_lvl, cur_lvl + 1])
		if node.right:
			st.append([node.right, next_lvl, cur_lvl + 1])

def print_tree(root):
	st = [[root, 'left']]
	l = []
	while len(st) > 0:
		(node, dir) = st.pop()
		if dir == 'left':
			st.append([node, 'right'])
			st.append([node, ''])
			if node.left:
				st.append([node.left, 'left'])
		elif dir == 'right':
			if node.right:
				st.append([node.right, 'left'])
		else:
			l.append(node.data)
	print(' '.join([str(n) for n in l]))

def main():
	n = int(input())
	root = read_nodes()
	k = int(input())
	for i in range(k):
		swap_level(root, int(input()))
		print_tree(root)
main()


class Node:

	def __init__(self, val=None, left=None, right=None):
		self.val = val
		self.left = left
		self.right = right
		self.depth = None

	def __str__(self):
		vals = []
		node = self
		to_process = []
		while node is not None or len(to_process) > 0:
			if node is None:
				node = to_process.pop()
				vals.append(node.val)
				node = node.right
				continue
			if node.left is not None:
				to_process.append(node)
				node = node.left
			else:
				vals.append(node.val)
				node = node.right
		return ' '.join([str(i) for i in vals])

	def swap(self, depth):
		target_depths = [depth * i for i in range(1, 1025)]
		node = self
		depth = 1
		to_swap = []
		to_process = []
		while node is not None or len(to_process) > 0:
			if node is None:
				node = to_process.pop()
				depth = node.depth
				if depth in target_depths:
					to_swap.append(node)
				node = node.right
				depth += 1
				continue
			if node.left is not None:
				node.depth = depth
				to_process.append(node)
				node = node.left
				depth += 1
			else:
				if depth in target_depths:
					to_swap.append(node)
				node = node.right
				depth += 1
		for node in to_swap:
			left_temp = node.left
			node.left = node.right
			node.right = left_temp
root = Node(1)
to_process = [root]
for n in range(int(input())):
	node = to_process.pop(0)
	vals = [int(i) for i in input().split()]
	if vals[0] != -1:
		node.left = Node(vals[0])
		to_process.append(node.left)
	if vals[1] != -1:
		node.right = Node(vals[1])
		to_process.append(node.right)
for swp in range(int(input())):
	k = int(input())
	root.swap(k)
	print(root)


class Node:

	def __init__(self, value, depth):
		self.value = str(value)
		self.left = None
		self.right = None
		self.depth = depth

def swap_nodes(nodes, level):
	for node in nodes:
		if node.depth % level == 0:
			hold = node.left
			node.left = node.right
			node.right = hold

def create_tree(nodes):
	for i in range(tree_input_count):
		node = nodes[i]
		(x, y) = input().split(' ')
		if x != '-1':
			node.left = Node(x, node.depth + 1)
			nodes.append(node.left)
		if y != '-1':
			node.right = Node(y, node.depth + 1)
			nodes.append(node.right)
	return nodes

def print_tree(node):
	result = []
	stack = []
	while len(stack) or node:
		if node:
			stack.append(node)
			node = node.left
		else:
			node = stack.pop()
			result.append(str(node.value))
			node = node.right
	print(' '.join(result))
tree_input_count = int(input())
root = Node(1, 1)
nodes = create_tree([root])
comands_count = int(input())
commands = []
for x in range(comands_count):
	commands.append(int(input()))
for command in commands:
	swap_nodes(nodes, command)
	print_tree(nodes[0])


import sys

def swap(cur, depth, tree, K):
	if cur not in tree:
		return
	left = tree[cur][0]
	right = tree[cur][1]
	if depth % K == 0:
		tree[cur] = [right, left]
	if left != -1:
		swap(left, depth + 1, tree, K)
	if right != -1:
		swap(right, depth + 1, tree, K)

def inorder(cur, tree):
	if cur not in tree:
		return
	s = ''
	if tree[cur][0] != -1:
		s += inorder(tree[cur][0], tree) + ' '
	s += str(cur)
	if tree[cur][1] != -1:
		s += ' ' + inorder(tree[cur][1], tree)
	return s
sys.setrecursionlimit(2000)
N = int(input().strip())
tree = {}
for i in range(N):
	(left, right) = map(int, input().strip().split())
	tree[i + 1] = [left, right]
T = int(input().strip())
for _ in range(T):
	swap(1, 1, tree, int(input().strip()))
	print(inorder(1, tree))


import sys
sys.setrecursionlimit(2048)
nodes = list((list((int(s) for s in input().split(' '))) for i in range(0, int(input()))))
swaps = list(([int(input())] for i in range(0, int(input()))))

class Node:
	data = None
	left = None
	right = None

	def __init__(self, data):
		self.data = data

	def set_children(self, data):
		if data[0] >= 0:
			self.left = Node(data[0])
		if data[1] >= 0:
			self.right = Node(data[1])

	def swap(self):
		temp = self.left
		self.left = self.right
		self.right = temp

class BinaryTree:
	root = Node(1)

	def __init__(self, data):
		i = 0

		def cb(node, depth):
			nonlocal i
			node.set_children(data[i])
			i += 1
		while i < len(data):
			self.inorder_traversal(cb, self.get_max_depth())

	def get_max_depth(self):
		max_depth = 1

		def cb(node, depth):
			nonlocal max_depth
			max_depth = max(max_depth, depth)
		self.inorder_traversal(cb)
		return max_depth

	def inorder_traversal(self, cb, at_depth=None):

		def traverse(node, depth):
			if node:
				traverse(node.left, depth + 1)
				if at_depth is None or at_depth == depth:
					cb(node, depth)
				traverse(node.right, depth + 1)
		traverse(self.root, 1)

	def __str__(self):
		datas = list()
		self.inorder_traversal(lambda node, depth: datas.append(str(node.data)))
		return ' '.join(datas)
tree = BinaryTree(nodes)
max_depth = tree.get_max_depth()
for i in range(0, len(swaps)):
	swap = swaps[i]
	m = 1
	while swap[len(swap) - 1] < max_depth:
		m += 1
		d = swap[0] * m
		if d <= max_depth:
			swap.append(d)
		else:
			break

	def cb(node, depth):
		if depth in swap:
			node.swap()
	for j in range(0, len(swap)):
		tree.inorder_traversal(lambda node, depth: node.swap(), swap[j])
	print(tree)


class Node:

	def __init__(self, data, left=None, right=None):
		self.data = data
		self.left = left
		self.right = right

def traverse_tree(root):
	(stack, node) = ([], root)
	while len(stack) > 0 or node is not None:
		if node is not None:
			stack.append(node)
			node = node.left
		else:
			node = stack.pop()
			yield node
			node = node.right

def print_tree(root):
	print(' '.join((str(node.data) for node in traverse_tree(root))))

def swap_subtrees(root, K):
	queue = [(1, root)]
	while len(queue) > 0:
		(depth, node) = queue.pop(0)
		if node is None:
			continue
		queue.append((depth + 1, node.left))
		queue.append((depth + 1, node.right))
		if depth % K == 0:
			(node.left, node.right) = (node.right, node.left)
N = int(input().strip())
nodes = [Node(n + 1) for n in range(N)]
for n in range(N):
	(l, r) = (int(x) - 1 for x in input().strip().split())
	if l >= 0:
		nodes[n].left = nodes[l]
	if r >= 0:
		nodes[n].right = nodes[r]
root = nodes[0]
T = int(input().strip())
for t in range(T):
	K = int(input().strip())
	swap_subtrees(root, K)
	print_tree(root)


def build_tree(N):
	tree = [[-1 for x in range(4)] for y in range(N)]
	for i in range(N):
		children = input()
		(left, right) = [int(x) for x in children.split(' ')]
		if left != -1:
			tree[i][0] = left - 1
		if right != -1:
			tree[i][1] = right - 1
		if tree[i][0] != -1:
			tree[tree[i][0]][2] = i
		if tree[i][1] != -1:
			tree[tree[i][1]][2] = i
	for i in range(N):
		d = 1
		j = i
		while tree[j][2] != -1:
			d += 1
			j = tree[j][2]
		tree[i][3] = d
	return tree

def inorder(tree):
	i = 0
	result = []
	stack = [0]
	while len(result) < len(tree):
		if tree[i][0] != -1 and tree[i][0] not in result:
			stack.append(i)
			i = tree[i][0]
		else:
			if i not in result:
				result += [i]
			if tree[i][1] != -1 and tree[i][1] not in result:
				stack.append(i)
				i = tree[i][1]
			else:
				i = stack.pop()
	return result

def inorder2(tree, i):
	left = tree[i][0]
	right = tree[i][1]
	result = []
	if left != -1:
		result += inorder(tree, left)
	result += [str(i + 1)]
	if right != -1:
		result += inorder(tree, right)
	return result

def print_tree(tree):
	print(' '.join([str(z + 1) for z in inorder(tree)]))

def swap(tree, D):
	for node in tree:
		if node[3] == D:
			tmp = node[0]
			node[0] = node[1]
			node[1] = tmp
	return tree
N = int(input())
tree = build_tree(N)
T = int(input())
for t in range(T):
	K = int(input())
	for i in range(N):
		swap(tree, (i + 1) * K)
	print_tree(tree)


class Node:

	def __init__(self, i):
		self.data = i
		(self.left, self.right) = (None, None)

def ReadInput():
	numNodes = int(input().strip())
	d = {}
	for i in range(1, numNodes + 1):
		n = Node(i)
		d[i] = n
	for i in range(1, numNodes + 1):
		n = d[i]
		lr = input().strip().split(' ')
		l = int(lr[0])
		r = int(lr[1])
		if l > 0:
			n.left = d[l]
		if r > 0:
			n.right = d[r]
	li = []
	for _ in range(int(input().strip())):
		li.append(int(input().strip()))
	return (d[1], li)

def InorderTraversal(node):
	if node == None:
		return []
	li = []
	cur = node
	st = []
	while True:
		if cur != None:
			st.append(cur)
			cur = cur.left
		elif len(st) > 0:
			cur = st.pop()
			li.append(str(cur.data))
			cur = cur.right
		else:
			break
	return li

def PrintResults(tree, heights):
	if tree == None:
		print('')
		return
	ht = 1
	d = {}
	st = [tree]
	while len(st) > 0:
		d[ht] = st
		ht += 1
		li = []
		for node in st:
			if node.left != None:
				li.append(node.left)
			if node.right != None:
				li.append(node.right)
		st = li
	for height in heights:
		mult = 1
		while height * mult in d:
			for node in d[height * mult]:
				(node.left, node.right) = (node.right, node.left)
			mult += 1
		print(' '.join(InorderTraversal(tree)))
(tree, heights) = ReadInput()
PrintResults(tree, heights)


import sys

class Node:

	def __init__(self, val, left=None, right=None):
		self.val = val
		self.left = left
		self.right = right

def traverse(n):
	order = []
	node = n
	nodestack = []

	def stack_left(nd):
		cn = nd
		nds = []
		while cn != None:
			nds.append(cn)
			cn = cn.left
		return nds
	nodestack += stack_left(node)
	while len(nodestack) != 0:
		node = nodestack.pop()
		order.append(node.val)
		if node.right != None:
			nodestack += stack_left(node.right)
	return order
stack = []
N = int(input())
root = Node(1)
stack.append(root)
for i in range(N):
	ns = [int(s) for s in input().split(' ')]
	cnode = stack.pop(0)
	if ns[0] != -1:
		left = Node(ns[0])
		cnode.left = left
		stack.append(left)
	if ns[1] != -1:
		right = Node(ns[1])
		cnode.right = right
		stack.append(right)
swaps = []
T = int(input())
for i in range(T):
	swaps.append(int(input()))

def levelswap(s):
	stack = [root]
	for i in range(1, s):
		if len(stack) == 0:
			return -1
		nstack = []
		while len(stack) != 0:
			node = stack.pop(0)
			if node.left != None:
				nstack.append(node.left)
			if node.right != None:
				nstack.append(node.right)
		stack = nstack
	while len(stack) != 0:
		n = stack.pop()
		tmp = n.left
		n.left = n.right
		n.right = tmp
	return 0
for s in swaps:
	n = 1
	while levelswap(s * n) == 0:
		n += 1
	print(' '.join([str(i) for i in traverse(root)]))


import sys
sys.setrecursionlimit(15000)

class Node(object):

	def __init__(self, left=None, right=None, val=None):
		self.left = left
		self.right = right
		self.val = val

def readInTree(nodeList, currLineNum, maxLineNum, listIndex):
	if currLineNum <= maxLineNum:
		lineArr = [int(arr_temp) for arr_temp in input().strip().split(' ')]
		currNode = nodeList[listIndex]
		if lineArr[0] != -1:
			leftNode = Node(None, None, lineArr[0])
			currNode.left = leftNode
			nodeList.append(leftNode)
		if lineArr[1] != -1:
			rightNode = Node(None, None, lineArr[1])
			currNode.right = rightNode
			nodeList.append(rightNode)
		readInTree(nodeList, currLineNum + 1, maxLineNum, listIndex + 1)

def populateInOrderList(node, listResults):
	if node.left is None and node.right is None:
		listResults.append(node.val)
	else:
		if node.left is not None:
			populateInOrderList(node.left, listResults)
		listResults.append(node.val)
		if node.right is not None:
			populateInOrderList(node.right, listResults)

def printCurrentTree(node):
	listResults = []
	populateInOrderList(rootNode, listResults)
	strResult = ''
	for i in range(0, len(listResults)):
		if i == 0:
			strResult += str(listResults[i])
		else:
			strResult += ' ' + str(listResults[i])
	print(strResult)

def performSwaps(node, currDepth, k):
	if node.left is not None or node.right is not None:
		if currDepth % k == 0:
			tempNode = node.right
			node.right = node.left
			node.left = tempNode
		if node.left is not None:
			performSwaps(node.left, currDepth + 1, k)
		if node.right is not None:
			performSwaps(node.right, currDepth + 1, k)
numNodes = int(input())
rootNode = Node(None, None, 1)
nodeList = []
nodeList.append(rootNode)
readInTree(nodeList, 1, numNodes, 0)
numSwaps = int(input())
for i in range(0, numSwaps):
	swapLevelK = int(input())
	performSwaps(rootNode, 1, swapLevelK)
	printCurrentTree(rootNode)


import sys
sys.setrecursionlimit(15000)

class Node:

	def __init__(self, value, left, right, depth):
		self.value = value
		self.left = left
		self.right = right
		self.depth = depth

def traverse(head):
	if head == None:
		return []
	res = traverse(head.left)
	res = res + [head.value]
	res = res + traverse(head.right)
	return res

def swap(head, depth):
	if head == None:
		return
	if head.depth == depth:
		tmp = head.left
		head.left = head.right
		head.right = tmp
		return
	swap(head.left, depth)
	swap(head.right, depth)
tree = {}
N = int(sys.stdin.readline().strip())
node = Node(1, None, None, 1)
tree[1] = node
max_height = 1
for value in range(1, N + 1):
	(left_value, right_value) = map(int, sys.stdin.readline().strip().split())
	node = tree.get(value)
	if left_value != -1:
		node.left = Node(left_value, None, None, node.depth + 1)
		tree[left_value] = node.left
	if right_value != -1:
		node.right = Node(right_value, None, None, node.depth + 1)
		tree[right_value] = node.right
	if (left_value != -1 or right_value != -1) and max_height < node.depth + 1:
		max_height = node.depth + 1
T = int(sys.stdin.readline().strip())
for line in sys.stdin.readlines():
	K = int(line.strip())
	iteration = 1
	while max_height >= K * iteration:
		swap(tree.get(1), K * iteration)
		iteration += 1
	print(' '.join(map(str, traverse(tree.get(1)))))


class Tree:

	def __init__(self, index):
		self.index = index

	def print(self):
		ind = []
		cur = self
		stack = []
		while cur or stack:
			if cur:
				stack.append(cur)
				cur = cur.L
			else:
				ind.append(stack[-1].index)
				cur = stack[-1].R
				stack.pop()
		print(' '.join([str(x) for x in ind]))

	def setSubTree(self, L, R):
		self.L = L
		self.R = R

	def swap(self):
		(self.L, self.R) = (self.R, self.L)
depth_map = {}
N = int(input())
trees = [None] + [Tree(i) for i in range(1, N + 1)] + [None]
trees[1].depth = 1
for n in range(1, N + 1):
	(l, r) = [int(x) for x in input().split()]
	trees[n].setSubTree(trees[l], trees[r])
	if trees[l]:
		trees[l].depth = trees[n].depth + 1
	if trees[r]:
		trees[r].depth = trees[n].depth + 1
	depth_map.setdefault(trees[n].depth, []).append(trees[n])
T = int(input())
for t in range(T):
	K = int(input())
	for i in range(N // K + 1):
		for tree in depth_map.get(i * K, []):
			tree.swap()
	trees[1].print()