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: Runtime Error

Solution code:
class NullNode():
    def __init__(self):
        self.id = None

class Node():
    def __init__(self, id):
        self.id = id
        self.parent = NullNode()
        self.left = NullNode()
        self.right = NullNode()

def preorder(node, out_list=[]):
    if node.id is not None:
        out_list.append(str(node.id))
        out_list = preorder(node.left, out_list)
        out_list = preorder(node.right, out_list)
    return out_list

def inorder(node, out_list=[]):
    if node.id is not None:
        out_list = inorder(node.left, out_list)
        out_list.append(str(node.id))
        out_list = inorder(node.right, out_list)
    return out_list

def insert(node, root_node):
    temp_node_parent = root_node.parent
    temp_node = root_node

    while temp_node.id is not None:
        temp_node_parent = temp_node
        if node.id < temp_node.id:
            temp_node = temp_node.left
        else:
            temp_node = temp_node.right

    node.parent = temp_node_parent
    if node.id < temp_node_parent.id:
        temp_node_parent.left = node
    else:
        temp_node_parent.right = node

# def find(id,root_node):
#     node = root_node
#     while node.id is not None:
#         if id < node.id:
#             node = node.left
#         elif id > node.id:
#             node = node.right
#         else:
#             print('yes')
#             break
#     else:
#         print('no')
#
# def delete(id, root_node):
#     # 作成中
#     type = ''
#     node = root_node
#     node_parent = NullNode()
#     while node.id != id:
#         node_parent = node
#         if id < node.id:
#             node = node.left
#             type = 'L'
#         else:
#             node = node.right
#             type = 'R'
#     if node.right is not None:
#         node.right.parent = node_parent
#     elif node.left is not None:
#         node.left.parent = node_parent
#     else:
#         node.parent = NullNode()
#
#     if type == 'L':
#         node_parent.left = NullNode()
#     else:
#         node_parent.right = NullNode()

n = int(input())
input_lines = sys.stdin.readlines()
root_node = NullNode()
for i in range(n):
    input_line = input_lines[i].split()
    command = input_line[0]
    if command == 'insert':
        id = int(input_line[1])
        id_node = Node(id)
        if root_node.id is None:
            root_node = id_node
        else:
            insert(id_node, root_node)

    # elif command == 'find':
    #     id = int(input_line[1])
    #     find(id, root_node)
    #
    # elif command == 'delete':
    #     id = int(input_line[1])
    #     delete(id, root_node)
    else:
        inorder_list = inorder(root_node, [])
        preorder_list = preorder(root_node, [])
        print(' ' + ' '.join(inorder_list))
        print(' ' + ' '.join(preorder_list))

Submission status: Runtime Error

Solution code:
def reconstruct(pre_list, in_list):
    if len(pre_list) <= 1:
        return pre_list
    now = pre_list[0]
    split_place = in_list.index(now)
    pre_left = pre_list[1:split_place + 1]
    in_left = in_list[0:split_place]
    pre_right = pre_list[split_place + 1:]
    in_right = in_list[split_place + 1:]
    return reconstruct(pre_left, in_left) + reconstruct(pre_right, in_right) + [now]

def print_list_split_whitespace(a):
    for x in a[:-1]:
        print(x, end=" ")
    print(a[-1])


n = int(input())
pre_list = [int(x) for x in input().split()]
in_list = [int(x) for x in input().split()]

post_list = reconstruct(pre_list, in_list)
print_list_split_whitespace(post_list)

Submission status: WA: Presentation Error

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

def insert(node, x):
    if node is None:
        return Node(x)
    elif x == node.key:
        return node
    elif x < node.key:
        node.left = insert(node.left, x)
    else:
        node.right = insert(node.right, x)
    return node

def preorder(node):
    if node == None:
        return None
    l.append(node.key)
    preorder(node.left)
    preorder(node.right)
    return l

def inorder(node):
    if node == None:
        return None
    inorder(node.left)
    l.append(node.key)
    inorder(node.right)
    return l

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

    def insert(self, x):
        self.root = insert(self.root, x)

    def output(self):
        print(self.root.key)
        print(self.root.left.key)
        print(self.root.right.key)

l = []
tree = BinaryTree()
n = int(input())

for i in range(n):
    order = list(map(str, input().split()))
    if order[0] == "insert":
        tree.insert(int(order[1]))
    if order[0] == "print":
        inorder(tree.root)
        for i in range(len(l)):
            if i != len(l)-1:
                print(l[i],end=" ")
            else:
                print(l[i])
        l.clear()

        preorder(tree.root)
        for i in range(len(l)):
            if i != len(l)-1:
                print(l[i],end=" ")
            else:
                print(l[i])
        exit()
    else:
        continue

Submission status: WA: Presentation Error

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

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

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

        if y == None: # Tが空の時
            self.max = z
            self.root = z
        elif v < y.key:
            y.left = z
        else :
            y.right = z
        if v > self.max.key:
            self.max = z

    # 先行
    def printPreorder(self, parent): # 最初はRootを与え再帰的に。
        print( str(parent.key), end="" )
        if parent != self.max:
            print("", end=" ")
        if parent.left != None:
            self.printPreorder(parent.left)
        if parent.right != None:
            self.printPreorder(parent.right)

    # 中間
    def printInorder(self, parent): # 最初はRootを与え再帰的に。
        if parent.left != None:
            self.printInorder(parent.left)
        print( str(parent.key), end="" )
        if parent != self.max:
            print("", end=" ")
        if parent.right != None:
            self.printInorder(parent.right)

def main():
    T = Tree()
    Orders =[]
    tmp =[]
    N = int( input() )
    for i in range(N):
        tmp = [input().split()]
        Orders.extend( tmp )

    for order in Orders:
        if order[0] == "insert":
            T.insert( int( order[1] ) )
        elif order[0] == "print":
            T.printInorder( T.root )
            print()
            T.printPreorder( T.root )
            print()

if __name__ == '__main__':
    main()

Submission status: WA: Presentation Error

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

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

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

        if y == None: # Tが空の時
            self.max = z
            self.root = z
        elif v < y.key:
            y.left = z
        else :
            y.right = z
        if v > self.max.key:
            self.max = z

    # 先行
    def printPreorder(self, parent): # 最初はRootを与え再帰的に。
        print( str(parent.key), end="" )
        if parent != self.max:
            print("", end=" ")
        if parent.left != None:
            self.printPreorder(parent.left)
        if parent.right != None:
            self.printPreorder(parent.right)

    # 中間
    def printInorder(self, parent): # 最初はRootを与え再帰的に。
        if parent.left != None:
            self.printInorder(parent.left)
        print( str(parent.key), end="" )
        if parent != self.max:
            print("", end=" ")
        if parent.right != None:
            self.printInorder(parent.right)

def main():
    T = Tree()
    Orders =[]
    tmp =[]
    N = int( input() )
    for i in range(N):
        tmp = [input().split()]
        Orders.extend( tmp )

    for order in Orders:
        if order[0] == "insert":
            T.insert( int( order[1] ) )
        elif order[0] == "print":
            T.printInorder( T.root )
            print()
            T.printPreorder( T.root )

if __name__ == '__main__':
    main()

Submission status: WA: Presentation Error

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

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

    def insert(self, v):
        self.n += 1
        y = None
        x = self.root
        while x != None:
            y = x
            if v < x.key:
                x = x.left
            else :
                x = x.right
        z = Node(v, y)

        if y == None: # Tが空の時
            self.root = z
        elif v < y.key:
            y.left = z
        else :
            y.right = z

    # 先行
    def printPreorder(self, parent): # 最初はRootを与え再帰的に。
        print( str(parent.key), end="" )
        self.count += 1
        if self.n > self.count:
            print("", end=" ")
        else :
            self.count = 0
        if parent.left != None:
            self.printPreorder(parent.left)
        if parent.right != None:
            self.printPreorder(parent.right)

    # 中間
    def printInorder(self, parent): # 最初はRootを与え再帰的に。
        if parent.left != None:
            self.printInorder(parent.left)
        print( str(parent.key), end="" )
        self.count += 1
        if self.n > self.count:
            print("", end=" ")
        else :
            self.count = 0
        if parent.right != None:
            self.printInorder(parent.right)

def main():
    T = Tree()
    Orders =[]
    tmp =[]
    N = int( input() )
    for i in range(N):
        tmp = [input().split()]
        Orders.extend( tmp )

    for order in Orders:
        if order[0] == "insert":
            T.insert( int( order[1] ) )
        elif order[0] == "print":
            T.printInorder( T.root )
            print()
            T.printPreorder( T.root )
            print()

if __name__ == '__main__':
    main()

Submission status: WA: Presentation Error

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

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

    def insert(self, v):
        self.n += 1
        y = None
        x = self.root
        while x != None:
            y = x
            if v < x.key:
                x = x.left
            else :
                x = x.right
        z = Node(v, y)

        if y == None: # Tが空の時
            self.root = z
        elif v < y.key:
            y.left = z
        else :
            y.right = z

    # 先行
    def printPreorder(self, parent): # 最初はRootを与え再帰的に。
        print( str(parent.key), end="" )
        self.count += 1
        if self.n > self.count:
            print("", end=" ")
        else :
            self.count = 0
        if parent.left != None:
            self.printPreorder(parent.left)
        if parent.right != None:
            self.printPreorder(parent.right)

    # 中間
    def printInorder(self, parent): # 最初はRootを与え再帰的に。
        if parent.left != None:
            self.printInorder(parent.left)
        print( str(parent.key), end="" )
        self.count += 1
        if self.n > self.count:
            print("", end=" ")
        else :
            self.count = 0
        if parent.right != None:
            self.printInorder(parent.right)

def main():
    T = Tree()
    Orders =[]
    tmp =[]
    N = int( input() )
    for i in range(N):
        tmp = [input().split()]
        Orders.extend( tmp )

    for order in Orders:
        if order[0] == "insert":
            T.insert( int( order[1] ) )
        elif order[0] == "print":
            T.printInorder( T.root )
            print()
            T.printPreorder( T.root )

if __name__ == '__main__':
    main()

Submission status: WA: Presentation Error

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

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

    def insert(self, v):
        self.n += 1
        y = None
        x = self.root
        while x != None:
            y = x
            if v < x.key:
                x = x.left
            else :
                x = x.right
        z = Node(v, y)

        if y == None: # Tが空の時
            self.root = z
        elif v < y.key:
            y.left = z
        else :
            y.right = z

    # 先行
    def printPreorder(self, parent): # 最初はRootを与え再帰的に。
        print( str(parent.key), end="" )
        self.count += 1
        if self.n > self.count:
            print("", end=" ")
        else :
            self.count = 0
        if parent.left != None:
            self.printPreorder(parent.left)
        if parent.right != None:
            self.printPreorder(parent.right)

    # 中間
    def printInorder(self, parent): # 最初はRootを与え再帰的に。
        if parent.left != None:
            self.printInorder(parent.left)
        print( str(parent.key), end="" )
        self.count += 1
        if self.n > self.count:
            print("", end=" ")
        else :
            self.count = 0
        if parent.right != None:
            self.printInorder(parent.right)

def main():
    T = Tree()
    Orders =[]
    tmp =[]
    N = int( input() )
    for i in range(N):
        tmp = [input().split()]
        Orders.extend( tmp )

    for order in Orders:
        if order[0] == "insert":
            T.insert( int( order[1] ) )
        elif order[0] == "print":
            T.printInorder( T.root )
            print("")
            T.printPreorder( T.root )

if __name__ == '__main__':
    main()

Submission status: WA: Presentation Error

Solution code:
#coding:utf-8

class MakeTree():
    def __init__(self, key, p=None, l=None, r=None):
        self.key = key
        self.p = p
        self.l = l
        self.r = r
 
def Insert(root,value):
    y = None
    x = root
    z = MakeTree(value)

    while x != None:
        y = x
        if x.key > z.key:
            x = x.l
        else:
            x = x.r
    z.p = y

    if y == None:
        root = z
    elif z.key < y.key:
        y.l = z
    else:
        y.r = z
    return root

def inParse(u):
    if u == None:
        return
    inParse(u.l)
    global inParseList
    inParseList.append(u.key)
    inParse(u.r)

def preParse(u):
    if u == None:
        return
    global preParseList
    preParseList.append(u.key)
    preParse(u.l)
    preParse(u.r)


root = None       
n = int(input())
inParseList = []
preParseList = []
for i in range(n):
    order = list(input().split())
    if order[0] == "insert":
        root = Insert(root, int(order[1]))
    else:
        inParse(root)
        preParse(root)

        print(" ".join([str(i) for i in inParseList]))
        print(" ".join([str(i) for i in preParseList]))

Submission status: WA: Presentation Error

Solution code:
class BinaryTree:

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


    def __init__(self):
        self.root = None

    def insert(self, key):
        if self.root is None:
            self.root = self.Node(key)
        else:
            root = self.root
            temp = None
            while True:
                temp = root
                if key > root.key:
                    root = root.right
                    if root is None:
                        temp.right = self.Node(key)
                        break
                else:
                    root = root.left
                    if root is None:
                        temp.left = self.Node(key)
                        break

    def print_inorder(self, node):
        if node is not None:
            self.print_inorder(node.left)
            print(node.key, end = " ")
            self.print_inorder(node.right)

    def print_preorder(self, node):
        if node is not None:
            print(node.key, end = " ")
            self.print_preorder(node.left)
            self.print_preorder(node.right)

    def test_insert(self, keys):
        for k in keys:
            self.insert(k)

length = int(input())
b = BinaryTree()
for _ in range(length):
    comm = input()
    if comm[0] == "i":
        com, num = comm.split(" ")
        b.insert(int(num))
    else:
        b.print_inorder(b.root)
        print(" ")
        b.print_preorder(b.root)
# 
# b.test_insert([30,88,12,1,20,17,25])
# b.print_inorder(b.root)
# print(" ")
# b.print_preorder(b.root)

Submission status: WA: Presentation Error

Solution code:
class BinaryTree:

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


    def __init__(self):
        self.root = None

    def insert(self, key):
        if self.root is None:
            self.root = self.Node(key)
        else:
            root = self.root
            temp = None
            while True:
                temp = root
                if key > root.key:
                    root = root.right
                    if root is None:
                        temp.right = self.Node(key)
                        break
                else:
                    root = root.left
                    if root is None:
                        temp.left = self.Node(key)
                        break

    def print_inorder(self, node):
        if node is not None:
            self.print_inorder(node.left)
            print(node.key, end = " ")
            self.print_inorder(node.right)

    def print_preorder(self, node):
        if node is not None:
            print(node.key, end = " ")
            self.print_preorder(node.left)
            self.print_preorder(node.right)

    def test_insert(self, keys):
        for k in keys:
            self.insert(k)

length = int(input())
b = BinaryTree()
for _ in range(length):
    comm = input()
    if comm[0] == "i":
        com, num = comm.split(" ")
        b.insert(int(num))
    else:
        print(" ", end = "")
        b.print_inorder(b.root)
        print(" ")
        b.print_preorder(b.root)
        print(" ", end = "")
        
# b.test_insert([30,88,12,1,20,17,25])
# b.print_inorder(b.root)
# print(" ")
# b.print_preorder(b.root)

Submission status: WA: Presentation Error

Solution code:


from io import StringIO
class BinaryTree:

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


    def __init__(self):
        self.root = None
        self.output = StringIO()

    def insert(self, key):
        if self.root is None:
            self.root = self.Node(key)
        else:
            root = self.root
            temp = None
            while True:
                temp = root
                if key > root.key:
                    root = root.right
                    if root is None:
                        temp.right = self.Node(key)
                        break
                else:
                    root = root.left
                    if root is None:
                        temp.left = self.Node(key)
                        break

    def ini_print_inorder(self):
        self.output = StringIO()
        self.print_inorder(self.root)
        return self.output.getvalue()

    def ini_print_preorder(self):
        self.output = StringIO()
        self.print_preorder(self.root)
        return self.output.getvalue()

    def print_inorder(self, node):
        if node is not None:
            self.print_inorder(node.left)
            print(node.key, end = " ", file = self.output)
            self.print_inorder(node.right)

    def print_preorder(self, node):
        if node is not None:
            print(node.key, end = " ", file = self.output)
            self.print_preorder(node.left)
            self.print_preorder(node.right)

    def test_insert(self, keys):
        for k in keys:
            self.insert(k)

length = int(input())
b = BinaryTree()
for _ in range(length):
    comm = input()
    if comm[0] == "i":
        com, num = comm.split(" ")
        b.insert(int(num))
    else:
        print(" ", end = "")
        print((b.ini_print_inorder())[:-1])
        print(b.ini_print_preorder()[:-1])

Submission status: WA: Presentation Error

Solution code:
import re

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

class BST:
  root = None
  def insert(self, k):
    x = self.root
    y = None
    z = Node(k)
    while x is not None:
      y = x
      if z.key < y.key:
        x = x.left
      elif y.key < z.key:
        x = x.right
    
    if y is None:
      # 初回値
      self.root = z
    else:
      if z.key < y.key:
        y.left = z
      elif y.key < z.key:
        y.right = z
        
  def inorder(self, r):
    # 中間巡回順で出力
    if r != None:
      self.inorder(r.left)
      print(" {}".format(r.key), end="")
      self.inorder(r.right)
      

  def preorder(self, r, lis):
    # 先行巡回順で出力
    if r != None:
      lis.append(r.key)
      self.preorder(r.left, lis)
      self.preorder(r.right, lis)

    
n = int(input())
bst = BST()
for _ in range(n):
  # query = [int(x) if re.match('[+|-]?\d', x) else x for x in input().split()]
  query = input().split()
  if query[0] == 'insert':
    bst.insert(int(query[1]))
  elif query[0] == 'print':
    root = bst.root
    lis = []
    bst.preorder(root, lis)
    print(" "+ " ".join(sorted(list(map(str, lis)))))
    print(" "+ " ".join(list(map(str, lis))))
    print()

Submission status: WA: Presentation Error

Solution code:
import re

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

class BST:
  root = None
  def insert(self, k):
    x = self.root
    y = None
    z = Node(k)
    while x is not None:
      y = x
      if z.key < y.key:
        x = x.left
      elif y.key < z.key:
        x = x.right
    
    if y is None:
      # 初回値
      self.root = z
    else:
      if z.key < y.key:
        y.left = z
      elif y.key < z.key:
        y.right = z
        
  def inorder(self, r):
    # 中間巡回順で出力
    if r != None:
      self.inorder(r.left)
      print(" {}".format(r.key), end="")
      self.inorder(r.right)
      

  def preorder(self, r, lis):
    # 先行巡回順で出力
    if r != None:
      lis.append(r.key)
      self.preorder(r.left, lis)
      self.preorder(r.right, lis)

    
n = int(input())
bst = BST()
for _ in range(n):
  # query = [int(x) if re.match('[+|-]?\d', x) else x for x in input().split()]
  query = input().split()
  if query[0] == 'insert':
    bst.insert(int(query[1]))
  elif query[0] == 'print':
    root = bst.root
    lis = []
    bst.preorder(root, lis)
    print(" "+ " ".join(sorted(list(map(str, lis)))) + " ")
    print(" "+ " ".join(list(map(str, lis))) + " ")

Submission status: WA: Presentation Error

Solution code:
import copy

def selection_sort(A,n):
    for i in range(n):
        minj = i
        for j in range(i,n):
            if A[j] < A[minj]:
                minj = j
        A[i],A[minj] = A[minj], A[i]
    return A

n = int(input())
r = [0]*n
for i in range(n):
    r[i] = input().split()

for i in range(n):
    if r[i][0] == "insert":
        root= int(r[i][1])
        key = i + 1
        break
    else:
        print()
        print()

left = []
right = []
for i in range(key, n):
    if r[i][0] == "insert" and int(r[i][1]) < root:
        left += [int(r[i][1])]
    elif r[i][0] == "insert" and int(r[i][1]) > root:
        right += [int(r[i][1])]
    else:
        pre = [root]+ left + right
        a = copy.deepcopy(pre)
        print(*selection_sort(a,len(a)))
        print(*pre)

Submission status: WA: Presentation Error

Solution code:
import copy

def selection_sort(A,n):
    for i in range(n):
        minj = i
        for j in range(i,n):
            if A[j] < A[minj]:
                minj = j
        A[i],A[minj] = A[minj], A[i]
    return A

n = int(input())
r = [0]*n
for i in range(n):
    r[i] = input().split()

for i in range(n):
    if r[i][0] == "insert":
        root= int(r[i][1])
        key = i + 1
        break
    

left = []
right = []
for i in range(key, n):
    if r[i][0] == "insert" and int(r[i][1]) < root:
        left += [int(r[i][1])]
    elif r[i][0] == "insert" and int(r[i][1]) > root:
        right += [int(r[i][1])]
    else:
        pre = [root]+ left + right
        a = copy.deepcopy(pre)
        print(*selection_sort(a,len(a)))
        print(*pre)

Submission status: WA: Presentation Error

Solution code:
import copy

def selection_sort(A,n):
    for i in range(n):
        minj = i
        for j in range(i,n):
            if A[j] < A[minj]:
                minj = j
        A[i],A[minj] = A[minj], A[i]
    return A

n = int(input())
r = [0]*n
for i in range(n):
    r[i] = input().split()

for i in range(n):
    if r[i][0] == "insert":
        root= int(r[i][1])
        key = i + 1
        break
    else:
        print()
        print()

left = []
right = []
for i in range(key, n):
    if r[i][0] == "insert" and int(r[i][1]) < root:
        left += [int(r[i][1])]
    elif r[i][0] == "insert" and int(r[i][1]) > root:
        right += [int(r[i][1])]
    else:
        pre = [root]+ left + right
        a = copy.deepcopy(pre)
        print(" ", *selection_sort(a,len(a)))
        print(" ", *pre)

Submission status: WA: Presentation Error

Solution code:
import copy

def selection_sort(A,n):
    for i in range(n):
        minj = i
        for j in range(i,n):
            if A[j] < A[minj]:
                minj = j
        A[i],A[minj] = A[minj], A[i]
    return A

n = int(input())
r = [0]*n
for i in range(n):
    r[i] = input().split()

for i in range(n):
    if r[i][0] == "insert":
        root= int(r[i][1])
        key = i + 1
        break
    else:
        print()
        print()

left = []
right = []
for i in range(key, n):
    if r[i][0] == "insert" and int(r[i][1]) < root:
        left += [int(r[i][1])]
    elif r[i][0] == "insert" and int(r[i][1]) > root:
        right += [int(r[i][1])]
    else:
        pre = [root]+ left + right
        a = copy.deepcopy(pre)
        print( *selection_sort(a,len(a)))
        print( *pre)

Submission status: WA: Presentation Error

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Mar  2 17:11:49 2019

@author: Yamazaki Kenichi
"""

m = int(input())
A = [list(input().split()) for i in range(m)]

T = [[-1,-1,-1,-1]]
def insert(T,u,x):
    if T[0][3] == -1:
        T[0][3] = x
        return
    if x < T[u][3]:
        if T[u][1] == -1:
            T[u][1] = len(T)
            T.append([u,-1,-1,x])
        else:
            insert(T,T[u][1],x)
    else:
        if T[u][2] == -1:
            T[u][2] = len(T)
            T.append([u,-1,-1,x])
        else:
            insert(T,T[u][2],x)
pre_res = []
def pre(u):
    pre_res.append(str(T[u][3]))
    if T[u][1] != -1:
        pre(T[u][1])
    if T[u][2] != -1:
        pre(T[u][2])
ino_res = []
def ino(u):
    if T[u][1] != -1:
        ino(T[u][1])
    ino_res.append(str(T[u][3]))
    if T[u][2] != -1:
        ino(T[u][2])

for c in A:
    if c[0] == 'insert':
        insert(T,0,int(c[1]))
    else:
        ino(0)
        pre(0)
        print(' '.join(ino_res))
        print(' '.join(pre_res))