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: WA: Presentation Error

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):
    if node is None:
        return
    inorder(node.left)
    # print("",end = " ")
    print(node.data,end = " ")
    inorder(node.right)
    # print("")
def preorder(node):
    if node is None:
        return
    # print("",end = " ")
    print(node.data,end = " ")
    preorder(node.left)
    preorder(node.right)
    # print("")

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

Submission status: WA: Presentation Error

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
    inorder(node.left)
    count += 1
    if count != this_len:
        print(node.data,end = " ")
    else:
        print(node.data)
    inorder(node.right)
def preorder(node):
    global count
    if node is None:
        return
    count += 1
    if count != this_len:
        print(node.data,end = " ")
    else:
        print(node.data)
    preorder(node.left)
    preorder(node.right)

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()

Submission status: WA: Presentation Error

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
    inorder(node.left)
    count += 1
    if count != this_len:
        print(node.data,end = " ")
    else:
        print(node.data)
    inorder(node.right)
def preorder(node):
    global count
    if node is None:
        return
    count += 1
    if count != this_len:
        print(node.data,end = " ")
    else:
        print(node.data,end = "")
    preorder(node.left)
    preorder(node.right)

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()

Submission status: WA: Presentation Error

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):
        return inorder(self.root)
    def b_preorder(self):
        return 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):
    nodelist = []
    if node.left:
        nodelist += inorder(node.left)
    nodelist += [node.data]
    if node.right:
        nodelist += inorder(node.right)
    return nodelist
def preorder(node):
    nodelist = [node.data]
    if node.left:
        nodelist += preorder(node.left)
    if node.right:
        nodelist += preorder(node.right)
    return nodelist

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

Submission status: WA: Presentation Error

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

    def insert(self, key):
        z = Node(key)
        y = None  # x?????????????´????????????°
        # z???parent???????´?
        x = self.root
        while x:
            y = x
            if z.key < x.key:
                x = x.left
            else:
                x = x.right
        z.parent = y
        # z??????????????´??????????´?
        if y is None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z

    def show(self):
        print(*list(map(str, self.root.inwalk())))
        print(*list(map(str, self.root.prewalk())))


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

    def prewalk(self):
        nodeList = [self.key]
        if self.left:
            nodeList += self.left.prewalk()
        if self.right:
            nodeList += self.right.prewalk()
        return nodeList

    def inwalk(self):
        nodeList = []
        if self.left:
            nodeList += self.left.inwalk()
        nodeList += [self.key]
        if self.right:
            nodeList += self.right.inwalk()
        return nodeList


tree = Tree()
P = []
I = []
n = int(input())
for i in range(n):
    cmd = list(input().split())
    if cmd[0] == 'insert':
        tree.insert(int(cmd[1]))
    else:
        tree.show()

Submission status: WA: Presentation Error

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

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

def inoder(x):
    if x == None: return []
    else:
        r = []
        r.extend(inoder(x.left))
        r.append(str(x.key))
        r.extend(inoder(x.right))
    return r

def preoder(x):
    if x == None: return []
    else:
        r = []
        r.append(str(x.key))
        r.extend(preoder(x.left))
        r.extend(preoder(x.right))
    return r

def show(x):
    print(" ".join(inoder(x)))
    print(" ".join(preoder(x)))


root = None
n = int(input())
for i in range(n):
    L = input().split()
    if L[0] == "insert":
        T = BinaryTree()
        T.key = int(L[1])
        insert(T)
    else:
        show(root)

Submission status: WA: Presentation Error

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(100000)

def insert(k, node):
    if k < node:
        if tree[node]["left"] == -1:
            tree[node]["left"] = k
            tree[k] = {"parent": node, "left": -1, "right": -1}
            return
        else:
            insert(k, tree[node]["left"])
    else:
        if tree[node]["right"] == -1:
            tree[node]["right"] = k
            tree[k] = {"parent": node, "left": -1, "right": -1}
            return
        else:
            insert(k, tree[node]["right"])


def pre_order(n):
    global pre_text
    
    if n == -1:
        return
    pre_text += "{} ".format(n)
    pre_order(tree[n]["left"])
    pre_order(tree[n]["right"])


def in_order(n):
    global in_text
    
    if n == -1:
        return

    in_order(tree[n]["left"])
    in_text += "{} ".format(n)
    in_order(tree[n]["right"])   

M = int(input())
root = "nan"
while root == "nan":
    inp = [n for n in input().split()]
    if inp[0] == "print":
        print()
        print()
    else:
        root = int(inp[1])

tree = {root:{"parent": -1, "left": -1, "right": -1}}

for _ in range(M-1):
    inp = [n for n in input().split()]
    if inp[0] == "print":
        in_text = ""
        pre_text = ""
        in_order(root)
        pre_order(root)
        print(in_text[:-1])
        print(pre_text[:-1])
    else:
        insert(int(inp[1]), root)

Submission status: WA: Presentation Error

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(100000)

def insert(k, node):
    if k < node:
        if tree[node]["left"] == None:
            tree[node]["left"] = k
            tree[k] = {"parent": node, "left": None, "right": None}
            return
        else:
            insert(k, tree[node]["left"])
    else:
        if tree[node]["right"] == None:
            tree[node]["right"] = k
            tree[k] = {"parent": node, "left": None, "right": None}
            return
        else:
            insert(k, tree[node]["right"])


def pre_order(n):
    result = []
    if n == None:
        return []
    result.append(str(n))
    result.extend(pre_order(tree[n]["left"]))
    result.extend(pre_order(tree[n]["right"]))
    
    return result


def in_order(n):
    result = []
    
    if n == None:
        return []

    result.extend(in_order(tree[n]["left"]))
    result.append(str(n))
    result.extend(in_order(tree[n]["right"]))
    
    return result


M = int(input())
root = "nan"
while root == "nan":
    inp = [n for n in input().split()]
    if inp[0] == "print":
        print()
        print()
    else:
        root = int(inp[1])

tree = {root:{"parent": None, "left": None, "right": None}}

for i, _ in enumerate(range(M-1)):
    inp = [n for n in input().split()]
    if inp[0] == "print":
        in_text = ""
        pre_text = ""
        print("" + " ".join(in_order(root)))
        print("" + " ".join(pre_order(root)))
    else:
        insert(int(inp[1]), root)
        #if i%1000 == 0:
        #    print("done {}/{}".format(i, M))

Submission status: WA: Presentation Error

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


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

    def insert(self, key):
        root_node = self.root
        insert_node = Node(key)
        parent_node = None

        while root_node:
            parent_node = root_node
            if insert_node.key < root_node.key:
                root_node = root_node.left
            else:
                root_node = root_node.right

        insert_node.parent = parent_node

        if parent_node is None:
            self.root = insert_node
        elif insert_node.key < parent_node.key:
            parent_node.left = insert_node
        else:
            parent_node.right = insert_node

    def show_preorder(self, node):
        node_list = []

        node_list.append(node.key)
        if node.left is not None:
            node_list.extend(self.show_preorder(node.left))
        if node.right is not None:
            node_list.extend(self.show_preorder(node.right))

        return node_list

    def show_inorder(self, node):
        node_list = []

        if node.left is not None:
            node_list.extend(self.show_inorder(node.left))
        node_list.append(node.key)
        if node.right is not None:
            node_list.extend(self.show_inorder(node.right))

        return node_list

    def print(self):
        print(*self.show_inorder(self.root))
        print(*self.show_preorder(self.root))


if __name__ == '__main__':
    tree = BinarySearchTree()

    n = int(input())

    for i in range(n):
        command = input().split()

        if command[0] == 'insert':
            tree.insert(int(command[1]))
        elif command[0] == 'print':
            tree.print()

Submission status: WA: Presentation Error

Solution code:
m = int(input())

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


class BinaryTree():
    def __init__(self):
        self.l = []

    def getRoot(self):
        return self.l[0] if len(self.l) > 0 else None

    def setRoot(self, v):
        self.l = [v] + self.l

    def inorder(self, v=None):
        if v is None:
            v = self.l[0]
        if v.left is not None:
            self.inorder(v.left)
        print(v.key, end=' ')
        if v.right is not None:
            self.inorder(v.right)
        
    def preorder(self, v=None):
        if v is None:
            v = self.l[0]
        print(v.key, end=' ')
        if v.left is not None:
            self.preorder(v.left)
        if v.right is not None:
            self.preorder(v.right)

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

    if y is None:
        T.setRoot(z)
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z

T = BinaryTree()

for i in range(m):
    inp = input().split()
    if inp[0] == 'print':
        T.inorder()
        print()
        T.preorder()
    else:
        v = Node(int(inp[1]), None, None)
        insert(T, v)

Submission status: WA: Presentation Error

Solution code:
m = int(input())

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


class BinaryTree():
    def __init__(self):
        self.l = []

    def getRoot(self):
        return self.l[0] if len(self.l) > 0 else None

    def setRoot(self, v):
        self.l = [v] + self.l

    def inorder(self, v=None):
        if v is None:
            v = self.l[0]
        if v.left is not None:
            self.inorder(v.left)
        print(' ' + str(v.key), end='')
        if v.right is not None:
            self.inorder(v.right)
        
    def preorder(self, v=None):
        if v is None:
            v = self.l[0]
        print(' ' + str(v.key), end='')
        if v.left is not None:
            self.preorder(v.left)
        if v.right is not None:
            self.preorder(v.right)

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

    if y is None:
        T.setRoot(z)
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z

T = BinaryTree()

for i in range(m):
    inp = input().split()
    if inp[0] == 'print':
        T.inorder()
        print()
        T.preorder()
    else:
        v = Node(int(inp[1]), None, None)
        insert(T, v)

Submission status: WA: Presentation Error

Solution code:
m = int(input())

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


class BinaryTree():
    def __init__(self):
        self.l = []

    def getRoot(self):
        return self.l[0] if len(self.l) > 0 else None

    def setRoot(self, v):
        self.l = [v] + self.l

    def inorder(self, v=None):
        if v is None:
            v = self.l[0]
        if v.left is not None:
            self.inorder(v.left)
        print(' ' + str(v.key), end='')
        if v.right is not None:
            self.inorder(v.right)
        
    def preorder(self, v=None):
        if v is None:
            v = self.l[0]
        print(' ' + str(v.key), end='')
        if v.left is not None:
            self.preorder(v.left)
        if v.right is not None:
            self.preorder(v.right)

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

    if y is None:
        T.setRoot(z)
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z

T = BinaryTree()

for i in range(m):
    inp = input().split()
    if inp[0] == 'print':
        T.inorder()
        print(' ')
        T.preorder()
    else:
        v = Node(int(inp[1]), None, None)
        insert(T, v)

Submission status: WA: Presentation Error

Solution code:
class BinarySearchTree:
    def __init__(self):
        self.root = None

    def insert(self, x):
        node = self.Node(x)
        if self.root is None:
            self.root = node
        else:
            here = self.root
            #
            temp = None
            while here is not None:
                temp = here
                if x < here.node:
                    here = here.left
                elif x > here.node:
                    here = here.right
            if x < temp.node:
                temp.left = node
            elif x > temp.node:
                temp.right = node

    def inorder(self, answer, address = "root"):
        if address is "root":
            address = self.root
        elif address is None:
            return
        self.inorder(answer, address.left)
        answer.append(address.node)
        self.inorder(answer, address.right)

    def preorder(self, answer, address = "root"):
        if address is "root":
            address = self.root
        elif address is None:
            return
        answer.append(address.node)
        self.preorder(answer, address.left)
        self.preorder(answer, address.right)

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

query = int(input())
bt = BinarySearchTree()
for _ in range(query):
    command = input()
    if command[0] == "i":
        bt.insert(int(command.split(" ")[1]))
    else:
        a = []
        bt.inorder(a)
        print(*a)
        a = []
        bt.preorder(a)
        print(*a)

Submission status: WA: Presentation Error

Solution code:
class BinarySearchTree:
    def __init__(self):
        self.root = None

    def insert(self, x):
        node = self.Node(x)
        if self.root is None:
            self.root = node
        else:
            here = self.root
            #
            temp = None
            while here is not None:
                temp = here
                if x < here.node:
                    here = here.left
                elif x > here.node:
                    here = here.right
            if x < temp.node:
                temp.left = node
            elif x > temp.node:
                temp.right = node

    def inorder(self, answer, address = "root"):
        if address is "root":
            address = self.root
        elif address is None:
            return
        self.inorder(answer, address.left)
        answer.append(address.node)
        self.inorder(answer, address.right)

    def preorder(self, answer, address = "root"):
        if address is "root":
            address = self.root
        elif address is None:
            return
        answer.append(address.node)
        self.preorder(answer, address.left)
        self.preorder(answer, address.right)

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

query = int(input())
bt = BinarySearchTree()
for _ in range(query):
    command = input()
    if command[0] == "i":
        bt.insert(int(command.split(" ")[1]))
    else:
        a = [" "]
        bt.inorder(a)
        
        print(*a)
        a = [" "]
        bt.preorder(a)
        print(*a)

Submission status: WA: Presentation Error

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


class Node(object):
    __slots__ = ["value", "left", "right"]

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


class BinTree(object):
    def __init__(self):
        self._tree = None

    def insert(self, value):
        parent = None
        current = self._tree

        while current is not None:
            parent = current
            if value < current.value:
                current = current.left
            else:
                current = current.right

        if parent is None:
            self._tree = Node(value)
        elif value < parent.value:
            parent.left = Node(value)
        else:
            parent.right = Node(value)

    def preoder_walk(self):
        def preoder(node):
            result = []
            if node is None:
                pass
            else:
                result.append(node.value)
                result.extend(preoder(node.left))
                result.extend(preoder(node.right))
            return result

        return preoder(self._tree)

    def inorder_walk(self):
        def inorder(node):
            result = []
            if node is None:
                pass
            else:
                result.extend(inorder(node.left))
                result.append(node.value)
                result.extend(inorder(node.right))
            return result

        return inorder(self._tree)


def print_tree(tree):
    print(" ".join([str(val) for val in tree.inorder_walk()]))
    print(" ".join([str(val) for val in tree.preoder_walk()]))


def insert_main(commands):
    tree = BinTree()
    for com in commands:
        if com[0] == "insert":
            tree.insert(int(com[1]))
        elif com[0] == "print":
            print_tree(tree)
        else:
            raise ValueError


if __name__ == "__main__":
    n = int(input())
    commands = [com.split() for com in sys.stdin.readlines()]
    insert_main(commands)

Submission status: WA: Presentation Error

Solution code:
NIL = None
class Tree:
    def __init__(self, key = None):
        self.key = key
        self.p = NIL
        self.left = NIL
        self.right = NIL
n = int(input())
tree = {"root":NIL}
def insert(T, z):
    y = NIL
    x = T["root"]
    while x != NIL:
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right
    z.p = y
    if y == NIL:
        T["root"] = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z
def preorder_tree_walk(T):
    print(f" {T.key}", end="")
    if T.left != NIL:
        preorder_tree_walk(T.left)
    if T.right != NIL:
        preorder_tree_walk(T.right)
def inorder_tree_walk(T):
    if T.left != NIL:
        inorder_tree_walk(T.left)
    print(f" {T.key}", end="")
    if T.right != NIL:
        inorder_tree_walk(T.right)
for _ in range(n):
    ss = input()
    if ss[0] == "i":
        s, v = ss.split()
        insert(tree, Tree(int(v)))
    else:
        inorder_tree_walk(tree["root"])
        print()
        preorder_tree_walk(tree["root"])

Submission status: WA: Presentation Error

Solution code:
import sys
readline = sys.stdin.readline
NIL = None
class Tree:
    def __init__(self, key = None):
        self.key = key
        self.p = NIL
        self.left = NIL
        self.right = NIL
n = int(input())
tree = {"root":NIL}
def insert(T, z):
    y = NIL
    x = T["root"]
    while x != NIL:
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right
    z.p = y
    if y == NIL:
        T["root"] = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z
def preorder_tree_walk(T):
    print(f" {T.key}", end="")
    if T.left != NIL:
        preorder_tree_walk(T.left)
    if T.right != NIL:
        preorder_tree_walk(T.right)
def inorder_tree_walk(T):
    if T.left != NIL:
        inorder_tree_walk(T.left)
    print(f" {T.key}", end="")
    if T.right != NIL:
        inorder_tree_walk(T.right)
for _ in range(n):
    ss = readline()
    if ss[0] == "i":
        s, v = ss.split()
        insert(tree, Tree(int(v)))
    else:
        inorder_tree_walk(tree["root"])
        print()
        preorder_tree_walk(tree["root"])

Submission status: WA: Presentation Error

Solution code:
# Binary Search Tree
class Node:
    def __init__(self, v):
        self.value = v
        self.parent = None
        self.left = None
        self.right = None

# 木の根を引数として受け取り，データを挿入した新しい木の根を返す
def insert(node, x):
    if node is None:
        return Node(x)
    elif x == node.value:
        return node
    elif x < node.value:
        node.left = insert(node.left, x)
    else:
        node.right = insert(node.right, x)
    return node

def preorder_walk(node):
    if node:
        yield node.value
        for x in preorder_walk(node.left):
            yield x
        for x in preorder_walk(node.right):
            yield x

def inorder_walk(node):
    if node:
        for x in inorder_walk(node.left):
            yield x
        yield node.value
        for x in inorder_walk(node.right):
            yield x

root = None
n = int(input())
for i in range(n):
    cmd, *val = input().split()
    if cmd == "insert":
        root = insert(root, int(val[0]))
    elif cmd == "print":
        print(*inorder_walk(root))
        print(*preorder_walk(root))