Problem:
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 ≠ 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.

Solution (Python):



class NodeBintree:

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

    def insert_node (self, n):
        if (self.key is None) or (self.key > n.key):
            if self.left is None:
                self.left = n
                
            else:
                self.left.insert_node(n)
        else:
            if self.right is None:
                self.right = n
                
            else:
                self.right.insert_node(n)

    def traverse_inorder (self):
        ret = ""

        if self.left is not None:
            ret += self.left.traverse_inorder()
            
            

        if self.key is not None:
            ret += " {0}".format(self.key)
            
            
            
            

        if self.right is not None:
            ret += self.right.traverse_inorder()
            
            
        return ret

    def traverse_preorder (self):
        ret = ""

        if self.key is not None:
            ret += " {0}".format(self.key)
            
            
            
            

        if self.left is not None:
            ret += self.left.traverse_preorder()
            
            

        if self.right is not None:
            ret += self.right.traverse_preorder()
            
            
        return ret

def proc_inputs ():
    num_inputs = int(input())
    inputs = [proc_command(input().split()) for i in range(num_inputs)]
    return inputs

def proc_command (l):
    if len(l) > 1:
        arg = l[1]
    else:
        arg = None
    return {"command": l[0], "arg": arg}

def execute_command (tree, command):
    if command["command"] == "insert":
        tree.insert_node(NodeBintree(int(command["arg"])))
        

    elif command["command"] == "print":
        print(tree.traverse_inorder() )
        
        print(tree.traverse_preorder() )
        
        
        
        
        
        
        
        

    return


def main ():
    inputs = proc_inputs()
    
    tree = NodeBintree(None)
    
    for command in inputs:
        execute_command(tree, command)
    exit(0)


if __name__ == "__main__":
    main()

Solution (Python):


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

def insert(root, z):
    y = None
    x = None
    if root != 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 printInOrder(z):
    if z == None:
        return
    if z.left != None:
        printInOrder(z.left)
    inorder.append(str(z.key))
    
    if z.right != None:
        printInOrder(z.right)
        
def printPreOrder(z):
    if z == None:
        return
    
    preorder.append(str(z.key))
    if z.left != None:
        printPreOrder(z.left)
    if z.right != None:
        printPreOrder(z.right)

root = None


n = int(input())
for i in range(n):
    command = input()
    if command[0] == "i":
        com,num = command.split()
        z = Node(int(num))
        insert(root, z)
        if root == None:
            root = z
    else:
        inorder = []
        printInOrder(root)
        print(" ", end = "")
        print(' '.join(inorder))
        preorder = []
        printPreOrder(root)
        print(" ", end = "")
        print(' '.join(preorder))

Solution (Python):
class BinarySearchTree:
    def __init__(self):
        self.lcs = {}
        self.rcs = {}
        self.root = None

    def insert(self, key):
        if self.root is None:
            self.root = key
            self.lcs[key] = None
            self.rcs[key] = None
            return
        parent = self.root
        while True:
            if key < parent:
                if self.lcs[parent] is None:
                    self.lcs[parent] = key
                    self.lcs[key] = None
                    self.rcs[key] = None
                    break
                else:
                    parent = self.lcs[parent]
            else:
                if self.rcs[parent] is None:
                    self.rcs[parent] = key
                    self.lcs[key] = None
                    self.rcs[key] = None
                    break
                else:
                    parent = self.rcs[parent]

    def _print(self, cur):
        self.preorder.append(cur)
        if self.lcs[cur]:
            self._print(self.lcs[cur])
        self.inorder.append(cur)
        if self.rcs[cur]:
            self._print(self.rcs[cur])

    def print(self):
        self.preorder = []
        self.inorder = []
        self._print(self.root)
        print(' ' + ' '.join(map(str, self.inorder)))
        print(' ' + ' '.join(map(str, self.preorder)))


T = BinarySearchTree()
N = int(input())
for _ in range(N):
    s = input().split()
    if s[0] == 'insert':
        T.insert(int(s[1]))
    else:
        T.print()

Solution (Python):

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

class Tree:
    def __init__(self):
        self.root = None
        self.list = []
    
    def insert(self, node_tobe_added):
            y = None 
            x = self.root
            while x != None:
                
                y = x
                if node_tobe_added.key < x.key:
                    x = x.left
                else:
                    x = x.right
            
            node_tobe_added.parent = y 
            
            
            if y == None:
                self.root = node_tobe_added
            elif node_tobe_added.key < y.key:
                
                y.left = node_tobe_added
            else:
                
                y.right = node_tobe_added
                
    def preParse(self, node):
        if node == None:
            return
        self.list.append(node.key)
        self.preParse(node.left)
        self.preParse(node.right)
    
    def inParse(self, node):
        if node == None:
            return
        self.inParse(node.left)
        self.list.append(node.key)
        self.inParse(node.right)

T = Tree()

N = int(input())
for i in range(N):
        order, *key = input().split() 
        if order == "print":
            T.list = []
            T.inParse(T.root)
            print(" " + " ".join(map(str, T.list)))
            T.list = []
            T.preParse(T.root)
            print(" " + " ".join(map(str, T.list)))
        else:
            T.insert(Node(int(key[0])))

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

class BinaryTree():
    def __init__(self):
        self.root = None
    
    def insert(self, value):
        if self.root == None:
            self.root = Node(value)
        else:
            parentnode = curnode = self.root
            while curnode != None:
                parentnode = curnode
                if curnode.value > value:
                    curnode = curnode.left
                else:
                    curnode = curnode.right
            if value > parentnode.value:
                parentnode.right = Node(value)
            else:
                parentnode.left = Node(value)

    def preorder(self, root):
        if root == None:
            pass
        else:
            print(' %d' % root.value, end='')
            self.preorder(root.left)
            self.preorder(root.right)

    def inorder(self, root):
        if root == None:
            pass
        else:
            self.inorder(root.left)
            print(' %d' % root.value, end='')
            self.inorder(root.right)

if __name__ == '__main__':
    n = int(input())
    binarytree = BinaryTree()
    for _ in range(n):
        common = input()
        if common[0] == 'i':
            binarytree.insert(int(common[7:]))
        else:
            binarytree.inorder(binarytree.root)
            print()
            binarytree.preorder(binarytree.root)
            print()

Solution (Python):

class Node:
    key = None
    parent = None
    left = None
    right = None

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


def insert(key):
    global T
    global root

    new_node = Node(key)
    T.append(new_node)

    if root is None:
        root = new_node

    else:
        y = None  
        x = root  

        while x is not None:
            y = x
            if key < x.key:
                x = x.left
            else:
                x = x.right

        new_node.parent = y
        if new_node.key < y.key:
            y.left = new_node
        else:
            y.right = new_node


def in_order(node, order):
    if node is None:
        return

    in_order(node.left, order)
    order.append(node.key)
    in_order(node.right, order)


def pre_order(node, order):
    if node is None:
        return

    order.append(node.key)
    pre_order(node.left, order)
    pre_order(node.right, order)


m = int(input())
T = []
root = None

for i in range(m):
    order = input()

    if order.startswith('print'):
        output = []
        in_order(root, output)
        
        print(' ' + ' '.join(map(str, output)))

        output = []
        pre_order(root, output)
        
        print(' ' + ' '.join(map(str, output)))

    else:
        order, value = order.split()
        value = int(value)
        insert(value)

Solution (Python):
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write

root = None
def insert(z):
    global root
    y = None
    x = root
    while x is not None:
        y = x
        if z[2] < x[2]:
            x = x[0]
        else:
            x = x[1]
    z[3] = y

    if y is None:
        root = z
    elif z[2] < y[2]:
        y[0] = z
    else:
        y[1] = z

def debug():
    s0 = [""]
    s1 = [""]

    def dfs(nd):
        v = str(nd[2])
        s0.append(v)
        if nd[0] is not None:
            dfs(nd[0])
        s1.append(v)
        if nd[1] is not None:
            dfs(nd[1])
    dfs(root)
    return " ".join(s1), " ".join(s0)


M = int(readline())
ans = []
for m in range(M):
    cmd, *V, = readline().split()
    if cmd == "print":
        ans.extend(debug())
    else:
        insert([None, None, int(V[0]), None])
write("\n".join(ans))
write("\n")

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

def insert(z):
    global root
    if root==None:
        root=Node(z)
    else:
        x=root
        while True:
            if z<x.key:
                if x.left:
                    x=x.left
                else:
                    x.left=Node(z)
                    break
            else:
                if x.right:
                    x=x.right
                else:
                    x.right=Node(z)
                    break
def inorder(z):
    if z==None:
        return []
    else:
        return inorder(z.left)+[z.key]+inorder(z.right)
def preorder(z):
    if z==None:
        return []
    else:
        return [z.key]+preorder(z.left)+preorder(z.right)
root=None
n=int(input())
for _ in range(n):
    p=input()
    if p[0]=="i":
        insert(int(p[7:]))
    else:
        print("",*inorder(root))
        print("",*preorder(root))

Solution (Python):
import sys
input = sys.stdin.readline
btree = []
root = None


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


def showInorder(node):
    if node.left is not None:
        showInorder(node.left)
    print(" {0}".format(str(node.key)), end="")
    if node.right is not None:
        showInorder(node.right)


def showPreorder(node):
    print(" {0}".format(node.key), end="")
    if node.left is not None:
        showPreorder(node.left)
    if node.right is not None:
        showPreorder(node.right)


def insert(key):
    global root
    z = Node(key, None, None, None)
    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 showtree(root):
    showInorder(root)
    print()
    showPreorder(root)
    print()


def main():
    m = int(input())
    global root
    for i in range(m):

        operation = input().split()

        

        if operation[0] == 'insert':
            
            insert(int(operation[1]))
        else:
            
            
            showtree(root)


if __name__ == '__main__':
    main()

Solution (Python):
class node:
    def __init__(self):
        self.p = -1
        self.l = -1
        self.r = -1

def preParse(u):
    if u == -1:
        return
    print(" " + str(u), end = '')
    preParse(T[u].l)
    preParse(T[u].r)

def inParse(u):
    if u == -1:
        return
    inParse(T[u].l)
    print(" " + str(u), end = '')
    inParse(T[u].r)

def postParse(u):
    if u == -1:
        return
    postParse(T[u].l)
    postParse(T[u].r)
    print(" " + str(u), end = '')

root = -1
def insert(T, z):
    global root
    parent = -1
    u = root
    while u != -1:
        parent = u
        if z < u:
            u = T[u].l
        else:
            u = T[u].r
    T[z].p = parent
    if parent == -1:
        root = z
    elif z < parent:
        T[parent].l = z
    else:
        T[parent].r = z


n = int(input())
cmdList = [input() for _ in range(n)]
T = {int(cmd[7:]): node() for cmd in cmdList if cmd[0] == "i"}

for cmd in cmdList:
    if cmd[0] == "p":
        inParse(root)
        print("")
        preParse(root)
        print("")
    else:
        insert(T, int(cmd[7:]))

Solution (Python):
class Node():
    """節クラス: valは節の値, parent/left/rightはそれぞれ親/左側の子/右側の子へのポインタを表す"""
    def __init__(self, val):
        self.val = val
        self.parent = None
        self.right = None
        self.left = None


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

    def search(self, val: int) -> bool:
        """二分木に値valを持つ節が存在するかどうか判定する
        根から順番に子を辿っていき、valと一致する節が存在する場合はTrue、存在しない場合はFalseを返す
        """
        ptr = self.root
        while ptr is not None:
            if ptr.val == val:
                return True
            if val < ptr.val:
                ptr = ptr.left
            else:
                ptr = ptr.right
        return False 

    def insert(self, val: int):
        """二分木に値valを持つ節を追加する（すでに二分木内に同じ要素が存在している場合も追加する）
        根から順番に子を辿っていき、ポインタが示す先に節が存在しなくなったらNode(val)として節を追加する
        """
        if self.root is None:
            
            self.root = Node(val)
            return

        ptr = self.root 
        while True:
            if val < ptr.val:
                if ptr.left is None:
                    
                    ptr.left = Node(val)
                    ptr.left.parent = ptr
                    return
                ptr = ptr.left
            else:
                if ptr.right is None:
                    
                    ptr.right = Node(val)
                    ptr.right.parent = ptr
                    return
                ptr = ptr.right
        
    def delete(self, val: int):
        """二分木から値valを持つ節を削除する
        根から順番に子を辿っていき、ptr.val == val が見つかったらptrをつなぎ替える。
        """
        if self.root is None:
            
            return 
        
        ptr = self.root
        
        while True: 
            if ptr is None:
                return
            if ptr.val == val:
                break
            elif val < ptr.val:
                ptr = ptr.left
            else:
                ptr = ptr.right
       
        
        if ptr.left is None and ptr.right is None:
            if ptr.parent.left == ptr:
                ptr.parent.left = None
            else:
                ptr.parent.right = None
        
        elif ptr.left is None:
            if ptr.parent.left == ptr:
                ptr.parent.left = ptr.right
                ptr.right.parent = ptr.parent
            else:
                ptr.parent.right = ptr.right
                ptr.right.parent = ptr.parent
        
        elif ptr.right is None:
            if ptr.parent.left == ptr:
                ptr.parent.left = ptr.left
                ptr.left.parent = ptr.parent
            else:
                ptr.parent.right = ptr.left
                ptr.left.parent = ptr.parent
        
        else:
            s = self.search_min(ptr.right)
            ptr.val = s.val
            if s.parent.left == s:
                s.parent.left = None
            else:
                s.parent.right = None            
    
    def search_min(self, ptr):
        """ptrを部分木の根としたときのptrの最小値の節へのポインタを返す
        ptr.leftをひたすら辿っていくことで可能"""
        while True:
            if ptr.left is None:
                return ptr
            ptr = ptr.left
            
    def rotate_left(self, ptr):
        """木を左回転する"""
        w = ptr.right
        w.parent = ptr.parent
        if w.parent is not None:
            if w.parent.left == ptr:
                w.parent.left = w
            else:
                w.parent.right = w
        ptr.right = w.left
        if ptr.right is not None:
            ptr.right.parent = ptr
        ptr.parent = w
        w.left = ptr
        if ptr == self.root:
            self.root = w
            self.root.parent = None

 
    def rotate_right(self, ptr):
        """木を右回転する"""
        w = ptr.left
        w.parent = ptr.parent
        if w.parent is not None:
            if w.parent.right == ptr:
                w.parent.right = w
            else:
                w.parent.left = w
        ptr.left = w.right
        if ptr.left is not None:
            ptr.left.parent = ptr
        ptr.parent = w
        w.right = ptr
        if ptr == self.root:
            self.root = w
            self.root.parent = None

    def preorder_tree_walk(self, ptr, res):
        """先行順巡回(preorder tree walk)"""
        if ptr is None:
            return res
        res.append(ptr.val)
        if ptr.left is not None:
            self.preorder_tree_walk(ptr.left, res)
        if ptr.right is not None:
            self.preorder_tree_walk(ptr.right, res)
        return res

    def inorder_tree_walk(self, ptr, res):
        """中間順巡回(inorder tree walk)"""
        if ptr is None:
            return res
        if ptr.left is not None:
            self.inorder_tree_walk(ptr.left, res)
        res.append(ptr.val)
        if ptr.right is not None:
            self.inorder_tree_walk(ptr.right, res)
        return res

    def postorder_tree_walk(self, ptr, res):
        """後行順巡回(postorder tree walk)"""
        if ptr is None:
            return res
        if ptr.left is not None:
            self.inorder_tree_walk(ptr.left, res)
        if ptr.right is not None:
            self.inorder_tree_walk(ptr.right, res)
        res.append(ptr.val)
        return res
      
      
n = int(input())
info = [list(input().split()) for i in range(n)]
bt = BinaryTree()

for i in range(n):
    if info[i][0] == "insert":
        bt.insert(int(info[i][1]))
    else:
        print(" ", end="")
        print(*bt.inorder_tree_walk(bt.root, res=[]))
        print(" ", end="")
        print(*bt.preorder_tree_walk(bt.root, res=[]))

Solution (Python):
num = int(input())
NIL = -1
MAX = 10000

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

class BST():
    def __init__(self):
        self.root = None
        self.In = []
        self.Pr = []
    
    def insert(self, data):
        n = self.root
        if n == None:
            self.root = Node(data)
            return 
        else:
            while True:
                entry = n.data
                if data < entry:
                    if n.left == None:
                        n.left = Node(data)
                        return
                    n = n.left
                elif data > entry:
                    if n.right == None:
                        n.right = Node(data)
                        return
                    n = n.right
                else:
                    n.data =data
                    return
                
    def inorder(self, node):
        if node != None:
            self.inorder(node.left)
            self.In.append(node.data)
            self.inorder(node.right)
        return self
    
    def preorder(self, node):
        if node != None:
            self.Pr.append(node.data)
            self.preorder(node.left)
            self.preorder(node.right)
        return self

a = BST()
for i in range(num):
    order = input().split()
    
    if order[0] == 'print':
        a.In = []
        a.Pr = []
        a.inorder(a.root)
        In = [str(j) for j in a.In]
        a.preorder(a.root)
        Pr = [str(j)  for j in a.Pr]
        print(' ' + ' '.join(In))
        print(' ' + ' '.join(Pr))
    else:
        order[1] = int(order[1])
        if i == 0:
            root = order[1]
        a.insert(order[1])

Solution (Python):



import sys
sys.setrecursionlimit(2**20)  


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


def pre_parse(T: dict, u: int, pre_ls: list):
    
    if u == None:
        return
    pre_ls.append(u)
    pre_parse(T, T[u].left, pre_ls)  
    pre_parse(T, T[u].right, pre_ls)


def in_parse(T, u, in_ls):
    if u == None:
        return
    
    in_parse(T, T[u].left, in_ls)
    in_ls.append(u)
    in_parse(T, T[u].right, in_ls)


def insert(T, ROOT, z):
    '''
    zは接点番号(そしてその接点番号が内容でもある)
    この接点番号を二分探索木の条件に従うように挿入する。
    '''
    
    if ROOT == z:
        T[z] = Node()
    
    else:
        T[z] = Node()  
        x = ROOT
        while x is not None:  
            next_parent = x  
            if z < x:  
                x = T[x].left
            else:
                x = T[x].right
        T[z].parent = next_parent
        
        if z < next_parent:
            T[next_parent].left = z
        else:
            T[next_parent].right = z


def print_result(T):
    pre_ls, in_ls = [], []
    in_parse(T, ROOT, in_ls)
    pre_parse(T, ROOT, pre_ls)
    print('', *in_ls)
    print('', *pre_ls)


    
N = int(input())
T = {}
for i in range(N):
    tmp = input()
    if tmp.startswith('print'):
        print_result(T)
    else:
        if len(tmp.split()) == 1:
            raise ValueError(tmp)
        command, z = tmp.split()[0], tmp.split()[1]
        z = int(z)
        if i == 0:
            ROOT = z
        insert(T, ROOT, z)

Solution (Python):
from typing import List, Optional


class Node:
	def __init__(self, key) -> None:
		self.key: int = key
		self.left: Optional[Node] = None
		self.right: Optional[Node] = None
		self.parent: Optional[Node] = None


class Tree:
	def __init__(self) -> None:
		self.root: Optional[Node] = None


def insert(T: Tree, z: Node) -> None:
	y: Optional[Node] = None
	x: Optional[Node] = T.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:
		T.root = z
	elif z.key < y.key:
		y.left = z
	else:
		y.right = z


def inorder(z: Optional[Node]):
	if z is not None:
		inorder(z.left)
		print(f" {z.key}", end="")
		inorder(z.right)


def preorder(z: Optional[Node]):
	if z is not None:
		print(f" {z.key}", end="")
		preorder(z.left)
		preorder(z.right)


if __name__ == "__main__":
	m = int(input())
	T = Tree()
	for _ in range(m):
		command = list(input().split())
		if command[0] == "insert":
			z = Node(int(command[1]))
			insert(T, z)
		else:
			inorder(T.root)
			print("")
			preorder(T.root)
			print("")

Solution (Python):
def preorder(T, index):
    print(" %d" %T[index][3], end="")
    if T[index][1] != -1:
        preorder(T, T[index][1])
    if T[index][2] != -1:
        preorder(T, T[index][2])


def inorder(T, index):
    if T[index][1] != -1:
        inorder(T, T[index][1])
    print(" %d" %T[index][3], end="")
    if T[index][2] != -1:
        inorder(T, T[index][2])

def insert(T, z):
    if len(T) == 0:
        T.append([0, -1, -1, z])
    else:
        i = 0
        T.append([0, -1, -1, z])
        while True:
            if T[i][3] > z and T[i][1] == -1:
                T[i][1] = len(T) - 1
                T[-1][0] = i
                break
            elif T[i][3] < z and T[i][2] == -1:
                T[i][2] = len(T) - 1
                T[-1][0] = i
                break
            elif T[i][3] > z:
                i = T[i][1]
            elif T[i][3] < z:
                i = T[i][2]


n = int(input())
a = [input().split() for _ in range(n)]

ans = []
for i in a:
    if i[0] == 'insert':
        insert(ans, int(i[1]))
    else:
        inorder(ans, 0)
        print("")
        preorder(ans, 0)
        print("")

Solution (Python):
import sys
from sys import stdin
input = stdin.readline

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

def Insert(parent, child):
    if parent.node > child.node:
        if parent.left != None:
            Insert(parent.left, child)
        else:
            parent.left = child
    else:
        if parent.right != None:
            Insert(parent.right, child)
        else:
            parent.right = child

IN_RESULT = []
def Inorder(root):
    if root.left == None:
        IN_RESULT.append(str(root.node))
        if root.right != None:
            Inorder(root.right)
    else:
        Inorder(root.left)
        IN_RESULT.append(str(root.node))
        if root.right != None:
            Inorder(root.right)
        else:
            pass
        
PRE_RESULT = []
def Preorder(root):
    PRE_RESULT.append(str(root.node))
    if root.left != None:
        Preorder(root.left)
    else:
        pass
    
    if root.right != None:
        Preorder(root.right)
    else:
        pass
    
    

n = int(input())


command = input()
if command[0] == "i":
    root = BinaryTreeNode(int(command[7:]))

for _ in range(n-1):
    command = input()
    if command[0] == "i":
        child = BinaryTreeNode(int(command[7:]))
        Insert(root, child)
        
    
    else:
        Inorder(root)
        Preorder(root)
        print(" "+" ".join(IN_RESULT))
        print(" "+" ".join(PRE_RESULT))
        IN_RESULT = []
        PRE_RESULT = []