Problem:

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

Binary Search Tree I

 Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue. 

  Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to satisfy the following binary search tree property:

 Let $x$ be a node in a binary search tree. If $y$ is a node in the left subtree of $x$, then $y.key \leq x.key$. If $y$ is a node in the right subtree of $x$, then $x.key \leq y.key$.

  The following figure shows an example of the binary search tree.

  For example, keys of nodes which belong to the left sub-tree of the node containing 80 are less than or equal to 80, and keys of nodes which belong to the right sub-tree are more than or equal to 80. The binary search tree property allows us to print out all the keys in the tree in sorted order by an inorder tree walk.

  A binary search tree should be implemented in such a way that the binary search tree property continues to hold after modifications by insertions and deletions. A binary search tree can be represented by a linked data structure in which each node is an object. In addition to a key field and satellite data, each node contains fields left, right, and p that point to the nodes corresponding to its left child, its right child, and its parent, respectively.

  To insert a new value $v$ into a binary search tree $T$, we can use the procedure insert as shown in the following pseudo code. The insert procedure is passed a node $z$ for which $z.key = v$, $z.left = NIL$, and $z.right = NIL$. The procedure modifies $T$ and some of the fields of $z$ in such a way that $z$ is inserted into an appropriate position in the tree.

1 insert(T, z)
2     y = NIL // parent of x
3     x = 'the root of T'
4     while x &ne; NIL
5         y = x // set the parent
6         if z.key < x.key
7             x = x.left // move to the left child
8         else 
9             x = x.right // move to the right child
10    z.p = y
11
12    if y == NIL // T is empty
13        'the root of T' = z
14    else if z.key < y.key
15        y.left = z // z is the left child of y
16    else 
17        y.right = z // z is the right child of y

  Write a program which performs the following operations to a binary search tree $T$.

insert  $k$: Insert a node containing $k$ as key into $T$.

print: Print the keys of the binary search tree by inorder tree walk and  preorder tree walk respectively.

  You should use the above pseudo code to implement the insert operation. $T$ is empty at the initial state.

Input

  In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$ or print are given.

Output

  For each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key.

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print

Sample Output 1

 1 12 17 20 25 30 88
 30 12 1 20 17 25 88

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.



Sample input:
8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print


Sample output:
 1 12 17 20 25 30 88
 30 12 1 20 17 25 88

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

class Node_Class():
    def __init__(self, key, parent, left, right):
        self.key = key
        self.parent = parent
        self.left = left
        self.right = right

def insert(z):
    global root
    y = None
    x = root
    while x is not None:
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right
    z.parent = y
    if y is None:
        root = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z

def pre_order(node):
    global pl
    if node is not None:
        pl.append(node.key)
        pre_order(node.left)
        pre_order(node.right)

def in_order(node):
    global il
    if node is not None:
        in_order(node.left)
        il.append(node.key)
        in_order(node.right)

m = int(raw_input())
root = None
pl = []
il = []
for i in range(m):
    line = map(str, raw_input().split())
    if line[0] == "insert":
        z = Node_Class(int(line[1]), None, None, None)
        insert(z)
    else:
        pre_order(root)
        in_order(root)
        print " "+" ".join(map(str, il))
        print " "+" ".join(map(str, pl))

Submission status: Wrong Answer

Solution code:
import sys
import time

class Node:
    def __init__(self, key = None):
        self.key = key
        self.left = None
        self.right = None

def insert(root, key):
    z = Node(key)
    y = None
    x = root
    while x:
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right

    if y is None:
        root.key = key
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z

def printBT(root):
    #print
    inorderTreeWalk(root)
    #print
    preorderTreeWalk(root)

def inorderTreeWalk(node):
    if node:
        return inorderTreeWalk(node.left) + " " + str(node.key) + inorderTreeWalk(node.right)
    return ""

def preorderTreeWalk(node):
    if node:
        return " " + str(node.key) + preorderTreeWalk(node.left) + preorderTreeWalk(node.right)
    return ""

if __name__ == "__main__":
    lines = sys.stdin.readlines()
    del lines[0]
    root = Node()
    inst = prit = 0
    start = time.time()
    for line in lines:
        if line[0] == "i":
            insert(root, int(line.split()[1]))
            inst += time.time() - start
        else:
            printBT(root)
            prit += time.time() - start
    print format(inst), format(prit)

Submission status: Wrong Answer

Solution code:
import sys
import time

class Node:
    def __init__(self, key = None):
        self.key = key
        self.left = None
        self.right = None

def insert(root, key):
    z = Node(key)
    y = None
    x = root
    while x:
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right

    if y is None:
        root.key = key
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z

def printBT(root):
    print inorderTreeWalk(root)
    print preorderTreeWalk(root)

def inorderTreeWalk(node):
    if node:
        return inorderTreeWalk(node.left) + " " + str(node.key) + inorderTreeWalk(node.right)
    return ""

def preorderTreeWalk(node):
    if node:
        return " " + str(node.key) + preorderTreeWalk(node.left) + preorderTreeWalk(node.right)
    return ""

if __name__ == "__main__":
    lines = sys.stdin.readlines()
    del lines[0]

    root = Node()
    for line in lines:
        if line[0] == "i":
            insert(root, int(line.split()[1]))
        else:
            printBT(root)

Submission status: Wrong Answer

Solution code:
class Node:
    def __init__(self,v):
        self.v = v
        self.left = None
        self.right = None

def inorder(n):
    if n != None:
        inorder(n.left)
        print n.v,
        inorder(n.right)

def preorder(n):
    if n != None:
        print n.v,
        preorder(n.left)
        preorder(n.right)

class BST:
    def __init__(self):
        self.root = None

    def insert(self,v):
        n = Node(v)
        x = self.root
        y = None
        while x != None:
            y = x
            if x.v > v:
                x = x.left
            else:
                x = x.right
        if y == None:
            self.root = n
        else:
            if y.v > v:
                y.left = n
            else:
                y.right = n
    def print_tree(self):
        print '',
        inorder(self.root)
        print
        print '',
        preorder(self.root)


n = int(raw_input())
ops = []
for _ in range(n):
    ops.append(raw_input())

tree = BST()
for op in ops:
    if op[0] == 'i':
        num = op.split(' ')[1]
        num = int(num)
        tree.insert(num)
    else:
        tree.print_tree()

Submission status: Wrong Answer

Solution code:
import sys

class Node():
    def __init__(self,key):
        self.key = key
        self.left = None
        self.right = None

def insert(t, z):
    y = None
    x = t
    while x is not None:
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right

    if y is None:
        return z
    else:
        if z.key < y.key:
            y.left = z
        else:
            y.right = z
        return t

def in_order(t):
    s = ""
    l = []
    curr = t
    while True:
        while curr is not None:
            l.append(curr)
            curr = curr.left
        if curr is None and len(l) == 0:
            break
        else:
            curr = l.pop()
            s += " " + str(curr.key)
            curr = curr.right
    return s

def pre_order(t):
    s = ""
    l = []
    curr = t
    while True:
        while curr is not None:
            s += " " + str(curr.key)
            l.append(curr)
            curr = curr.left
        if curr is None and len(l) == 0:
            break
        else:
            curr = l.pop()
            curr = curr.right
    return s

t = None
n = sys.stdin.readline()
lines = sys.stdin.readlines()
for line in lines:
    com = line.split()
    if line[0] == "insert":
        t = insert(t, Node(int(com[1])))
    else:
        print(in_order(t))
        print(pre_order(t))

Submission status: Wrong Answer

Solution code:
class node(object):

    def __init__(self,key = 0, parent = None):
        self.key = key
        self.parent, self.right, self.left = parent,None,None



def insert(T, z):

    if z < T.key:
        if T.left == None:
            k = node(key=z,parent = T)
            T.left = k
            return
        else:
            insert(T.left, z)
            return
    else:
        if T.right == None:
            k = node(key=z,parent = T)
            T.right = k
            return

        else:
            insert(T.right, z)
            return

def disp_tree(root):
    print(root.key,' ',end='')
    if root.left != None:
        disp_tree(root.left)

    if root.right != None:
        disp_tree(root.right)

    return

def disp_tree2(root):
    if root == None:
        return
    else:
        disp_tree2(root.left)

        print(root.key,' ',end='')

        disp_tree2(root.right)

def disp(root):
    disp_tree2(root)
    print('\b')
    disp_tree(root)
    print('\b')


n = int(input())
f = 0
root = node()

for i in range(n):
    input_data = input().split()
    if len(input_data) >= 2:
        command = input_data[0]
        key = int(input_data[1])
        if f == 0 :
            root = node()
            root.key  = key
            f = 1
        else :
            insert(root,key)
    else :
        disp(root)

Submission status: Wrong Answer

Solution code:
def insert(r, n):
    if 0 == len(T):
        T[n] = [None, None]
    else:
        if n < r:
            left = T[r][0]
            if left == None:
                T[r][0] = n
                T[n] = [None, None]
            else:
                insert(left, n)
        if r < n:
            right = T[r][1]
            if right == None:
                T[r][1] = n
                T[n] = [None, None]
            else:
                insert(right, n)

def print_inorder(r):
    left = T[r][0]
    right = T[r][1]
    ans = ""
    if left != None:
        ans += print_inorder(left)
    ans += " {}".format(r)
    if right != None:
        ans += print_inorder(right)
    return ans

def print_preorder(r):
    left = T[r][0]
    right = T[r][1]
    ans = " {}".format(r)
    if left != None:
        ans += print_inorder(left)
    if right != None:
        ans += print_inorder(right)
    return ans




n = int(input())
T = {}

root = None
for i in range(n):
    inst = input()
    if inst[0] == 'i':
        num = int(inst[7:])
        if i == 0:
            root = num
        insert(root, num)
    elif inst[0] == 'p':
        print(print_inorder(root))
        print(print_preorder(root))

Submission status: Wrong Answer

Solution code:
#coding:UTF-8
class Node:
    def __init__(self,point):
        self.n=point
        self.left=None
        self.right=None
        
def insert(t,z):
    y=None
    x=t
    while x!=None:
        y=x
        if z.n<x.n:
            x=x.left
        else:
            x=x.right
    if y==None:
        return z
    else:
        if z.n<y.n:
            y.left=z
        else:
            y.right=z
        return t

def Pre(t,l):
    l.append(t.n)
    if t.left!=None:
        Pre(t.left,l)
    if t.right!=None:
        Pre(t.right,l)

def In(t,l):
    if t.left!=None:
        In(t.left,l)
    l.append(t.n)
    if t.right!=None:
        In(t.right,l)

def BST1(A,n):
    tree=None
    for i in range(n):
        if A[i]=="print":
            PreAns=[]
            InAns=[]
            Pre(tree,PreAns)
            In(tree,InAns)
            print(" ",*PreAns)
            print(" ",*InAns)
        else:
            z=Node(int(A[i].split(" ")[1]))
            tree=insert(tree,z)
            
if __name__=="__main__":
    n=int(input())
    A=[]
    for i in range(n):
        A.append(input())
    BST1(A,n)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
input:
8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print

output: in_order + pre_order
1 12 17 20 25 30 88
30 12 1 20 17 25 88

def pre_order(node):
    if node is not None:
        print('', node.data, end='')
        pre_order(node.left)
        pre_order(node.right)
    return None


def in_order(node):
    if node is not None:
        in_order(node.left)
        print('', node.data, end='')
        in_order(node.right)
    return None
    
 def tree_data(self):
        stack = []
        node = self
        while stack or node:
            if node:
                stack.append(node)
                node = node.left
            else:
                node = stack.pop()
                yield node.data
                node = node.right
"""

import sys


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

    def insert(self, data):
        """
        insert data according to BST rules
        """
        if data < self.data:
            if self.left is None:
                self.left = Node(data)
            else:
                self.left.insert(data)
        else:
            if self.right is None:
                self.right = Node(data)
            else:
                self.right.insert(data)

        return None


def in_order(node):
    if node is not None:
        in_order(node.left)
        print('', node.data, end='')
        in_order(node.right)
    return None


def pre_order(node):
    if node is not None:
        print('', node.data, end='')
        pre_order(node.left)
        pre_order(node.right)
    return None


def action(command, content):
    if command[0] == 'i':
        tree_root.insert(data=int(content))

    elif command[0] == 'p':
        pre_order(tree_root)
        print('')
        in_order(tree_root)
        print('')

    return None


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    array_length = int(_input[0])
    command_list = list(map(lambda x: x.split(), _input[1:]))
    # assert len(command_list) == array_length
    # print(array_length, *command_list)

    flag, tree_root = False, None
    for each in command_list:
        command, content = each[0], each[-1]
        if (not flag) and command.startswith('in'):
            tree_root = Node(data=int(content))
            flag = True
            continue
        action(command=command, content=content)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
input:
8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print

4
insert 3
insert 2
insert 4
print

output: in_order + pre_order
1 12 17 20 25 30 88
30 12 1 20 17 25 88
"""

import sys


class Node(object):
    def __init__(self, data):
        self.data = data
        self.left, self.right = None, None
        self.pre_order = []

    def insert(self, data):
        """
        insert data according to BST rules
        """
        if data < self.data:
            if self.left is None:
                self.left = Node(data)
            else:
                self.left.insert(data)
        else:
            if self.right is None:
                self.right = Node(data)
            else:
                self.right.insert(data)

        return None

    @property
    def in_order_data(self):
        stack = []
        node = self
        while stack or node:
            if node:
                stack.append(node)
                self.pre_order.append(node.data)
                node = node.left
            else:
                node = stack.pop()
                yield node.data
                node = node.right


def action(command, content):
    if command.startswith('in'):
        tree_root.insert(data=int(content))

    elif command.startswith('pr'):
        print('', *tree_root.in_order_data)
        print('', *tree_root.pre_order)

    return None


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    array_length = int(_input[0])
    command_list = list(map(lambda x: x.split(), _input[1:]))
    # assert len(command_list) == array_length
    # print(array_length, *command_list)

    flag, tree_root = True, None
    for each in command_list:
        command, content = each[0], each[-1]
        if flag and command.startswith('in'):
            tree_root = Node(data=int(content))
            flag = False
            continue
        action(command=command, content=content)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

import random
import sys
import os


class Tree:
    def __init__(self):
        self.root = None

    def __str__(self):
        if self.root == None:
            return None
        else:
            return "TODO"

    def print_inorder(self):
        self.__inorder(self.root)

    def __inorder(self, node):
        """
        :param node: Node
        :return:
        """
        if node is None:
            return
        else:
            self.__inorder(node.left)
            print(node.key, end=' ')
            self.__inorder(node.right)

    def print_preorder(self):
        self.__preorder(self.root)

    def __preorder(self, node):
        """
        :param node: Node
        :return:
        """
        if node is None:
            return
        else:
            print(node.key, end=' ')
            self.__preorder(node.left)
            self.__preorder(node.right)

    def insert(self, node):
        """
        :param node: Node
        :return:
        """
        if self.root is None:
            self.root = node
        else:
            x = self.root
            parent_candidate = x

            while x is not None:
                parent_candidate = x
                if x.key > node.key:
                    x = x.left
                else:
                    x = x.right

            # child to parent link
            x = node
            x.parent = parent_candidate

            # parent to child link
            if x.key < x.parent.key:
                x.parent.left = x
            else:
                x.parent.right = x

    def find(self, value):
        """
        :param value:
        :rtype: Node
        :return:
        """
        x = self.root
        while x is not None and x.key != value:
            if x.key > value:
                x = x.left
            else:
                x = x.right
        return x

    def delete(self, value):
        found_node = self.find(value)
        if found_node is None:
            print("value is nothing")
        else:
            # has no child
            if found_node.is_leaf():
                # delete link from parent
                print(found_node.parent.left.key)
                print(found_node.key)

                if found_node.parent.left.key == found_node.key:
                    found_node.parent.left = None
                else:
                    found_node.parent.right = None
            else:
                # has one child
                if found_node.has_one_child():
                    one_child = found_node.get_one_child()

                    # change link to parent
                    one_child.parent = found_node.parent

                    # chagne link from parent
                    if found_node.parent.left == found_node:
                        found_node.parent.left = one_child
                    else:
                        found_node.parent.right = one_child

                # has two child
                else:
                    next_section_point = found_node.get_next_section_point()
                    # ?¬???????????????????????????????????????????????¬?????????????????????? p217
                    # ????????????
                    key = next_section_point.key
                    self.delete(next_section_point.key)
                    found_node.key = key


class Node:
    def __init__(self, key):
        self.parent = None  # type: Node
        self.left = None  # type: Node
        self.right = None  # type: Node
        self.key = key  # type: int

    def has_one_child(self):
        if self.left is None and self.right is not None:
            return True
        elif self.left is not None and self.right is None:
            return True
        else:
            return False

    def get_one_child(self):
        if not self.has_one_child():
            return None
        else:
            if self.left is not None:
                return self.left
            else:
                return self.right

    def get_next_section_point(self):
        """?¬??????????????????????"""

        # ????????????????????´???
        if self.right is not None:
            return self.right.get_minimum()
        # ???????????????????????´???????¬???????????????´?????????
        else:
            # ?
            return self.parent

    def is_leaf(self):
        if self.left is None and self.right is None:
            return True
        else:
            return False

    def get_minimum(self):
        if self.left is None:
            return self
        else:
            return self.left.get_minimum()

tree = Tree()
s = input()
n = int(s)
for _ in range(n-1):
    s = input()
    value = int(s.split(" ")[-1])
    node = Node(value)
    tree.insert(node)
tree.print_preorder()
print('')
tree.print_inorder()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

import random
import sys
import os


class Tree:
    def __init__(self):
        self.root = None

    def __str__(self):
        if self.root == None:
            return None
        else:
            return "TODO"

    def print_inorder(self):
        self.inorder_list = []
        self.__inorder(self.root)
        return self.inorder_list

    def __inorder(self, node):
        """
        :param node: Node
        :return:
        """
        if node is None:
            return
        else:
            self.__inorder(node.left)
            self.inorder_list.append(node.key)
            self.__inorder(node.right)

    def print_preorder(self):
        self.preorder_list = []
        self.__preorder(self.root)
        return self.preorder_list

    def __preorder(self, node):
        """
        :param node: Node
        :return:
        """
        if node is None:
            return
        else:
            self.preorder_list.append(node.key)
            self.__preorder(node.left)
            self.__preorder(node.right)

    def insert(self, node):
        """
        :param node: Node
        :return:
        """
        if self.root is None:
            self.root = node
        else:
            x = self.root
            parent_candidate = x

            while x is not None:
                parent_candidate = x
                if x.key > node.key:
                    x = x.left
                else:
                    x = x.right

            # child to parent link
            x = node
            x.parent = parent_candidate

            # parent to child link
            if x.key < x.parent.key:
                x.parent.left = x
            else:
                x.parent.right = x

    def find(self, value):
        """
        :param value:
        :rtype: Node
        :return:
        """
        x = self.root
        while x is not None and x.key != value:
            if x.key > value:
                x = x.left
            else:
                x = x.right
        return x

    def delete(self, value):
        found_node = self.find(value)
        if found_node is None:
            print("value is nothing")
        else:
            # has no child
            if found_node.is_leaf():
                # delete link from parent
                print(found_node.parent.left.key)
                print(found_node.key)

                if found_node.parent.left.key == found_node.key:
                    found_node.parent.left = None
                else:
                    found_node.parent.right = None
            else:
                # has one child
                if found_node.has_one_child():
                    one_child = found_node.get_one_child()

                    # change link to parent
                    one_child.parent = found_node.parent

                    # chagne link from parent
                    if found_node.parent.left == found_node:
                        found_node.parent.left = one_child
                    else:
                        found_node.parent.right = one_child

                # has two child
                else:
                    next_section_point = found_node.get_next_section_point()
                    # ?¬???????????????????????????????????????????????¬?????????????????????? p217
                    # ????????????
                    key = next_section_point.key
                    self.delete(next_section_point.key)
                    found_node.key = key


class Node:
    def __init__(self, key):
        self.parent = None  # type: Node
        self.left = None  # type: Node
        self.right = None  # type: Node
        self.key = key  # type: int

    def has_one_child(self):
        if self.left is None and self.right is not None:
            return True
        elif self.left is not None and self.right is None:
            return True
        else:
            return False

    def get_one_child(self):
        if not self.has_one_child():
            return None
        else:
            if self.left is not None:
                return self.left
            else:
                return self.right

    def get_next_section_point(self):
        """?¬??????????????????????"""

        # ????????????????????´???
        if self.right is not None:
            return self.right.get_minimum()
        # ???????????????????????´???????¬???????????????´?????????
        else:
            # ?
            return self.parent

    def is_leaf(self):
        if self.left is None and self.right is None:
            return True
        else:
            return False

    def get_minimum(self):
        if self.left is None:
            return self
        else:
            return self.left.get_minimum()

tree = Tree()
s = input()
n = int(s)
for _ in range(n-1):
    s = input()
    value = int(s.split(" ")[-1])
    node = Node(value)
    tree.insert(node)

pre_list = tree.print_preorder()
pre_list = map(str, pre_list)
print(' '.join(pre_list))

in_list = tree.print_inorder()
in_list = map(str, in_list)
print(' '.join(in_list))

Submission status: Wrong Answer

Solution code:
treeRoot = {'left': None, 'right': None, 'p': None, 'val': None}

root = None

def insert(val):
    global root
    z = {'left': None, 'right': None, 'p': None, 'val': val}
    x = root
    y = None
    while x:
        y = x
        if z['val'] < x['val']:
            x = x['left']
        else:
            x = x['right']
    z['p'] = y
    if y is None:
        root = z
    else:
        if z['val'] < y['val']:
            y['left'] = z
        else:
            y['right'] = z


def inorder(root):
    if root is None:
        return
    inorder(root['left'])
    print(root['val'])
    inorder(root['right'])


def preorder(root):
    if root is None:
        return
    print(root['val'])
    preorder(root['left'])
    preorder(root['right'])


M = int(input())
for _ in range(M):
    line = input()
    if line == 'print':
        inorder(root)
        preorder(root)
        break
    inst, k = line.split()
    k = int(k)
    if inst == 'insert':
        insert(k)
    elif inst == 'find':
        pass
    elif inst == 'delete':
        pass

Submission status: Wrong Answer

Solution code:
class BinaryTree:
    def __init__(self):
        self.root = None
    def b_insert(self,x):
        self.root = insert(self.root,x)
    def b_inorder(self):
        inorder(self.root)
    def b_preorder(self):
        preorder(self.root)
        
class Node:
    def __init__(self,x):
        self.data = x
        self.left = None
        self.right = None
            
def insert(node,x):
    if node is None:
        return Node(x)
    elif x == node.data:
        return node
    elif x < node.data:
        node.left = insert(node.left,x)
    else:
        node.right = insert(node.right,x)
    return node
def inorder(node):
    global count
    if node is None:
        return
    count += 1
    inorder(node.left)
    # print("",end = " ")
    if count != this_len:
        print(node.data,end = " ")
    else:
        print(node.data)
    inorder(node.right)
    # print("")
def preorder(node):
    global count
    if node is None:
        return
    # print("",end = " ")
    count += 1
    if count != this_len:
        print(node.data,end = " ")
    else:
        print(node.data)
    preorder(node.left)
    preorder(node.right)
    # print("")

length = int(input())
bfs = BinaryTree()
this_len = 0
for l in range(length):
    temp = input()
    if temp[0] == 'i':
        command,num = (n for n in temp.split(" "))
        bfs.b_insert(int(num))
        this_len += 1
    else:
        count = 0
        bfs.b_inorder()
        count = 0
        bfs.b_preorder()