Binary Search Tree I

Search trees are dynamic data structures supporting operations like insert, search, and delete. They can function as dictionaries and priority queues. A binary search tree is a fundamental search tree where keys are stored to satisfy the binary search tree property: for any node x, if y is in the left subtree of x, then y.key ≤ x.key; if y is in the right subtree of x, then x.key ≤ y.key.

A binary search tree can be used to print keys in sorted order through an inorder tree walk. It should maintain the binary search tree property after insertions and deletions. Each node in the tree has a key, satellite data, and fields left, right, and p pointing to its left child, right child, and parent, respectively.

To insert a new value v into a binary search tree T, the insert procedure is used. The program should perform insert and print operations on the binary search tree T. The insert operation uses the provided pseudo code. T is initially empty.

Input:
The first line contains the number of operations m. The following m lines contain insert k or print operations.

Output:
For each print operation, print the keys obtained by inorder and preorder tree walks on a single line, with a space before each key.

Constraints:
- The number of operations ≤ 500,000
- The number of print operations ≤ 10
- -2,000,000,000 ≤ key ≤ 2,000,000,000
- The height of the binary tree does not exceed 100 using the provided 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.

# Buggy version:
class binaryTree:
    def __init__(self,key,p=None,l=None,r=None):
        self.key = key
        self.p = p
        self.l = l
        self.r = r

N = int(input())
treelist = [list(input().split()) for i in range(N)]
root = None

def inorder(root):
    x = root
    if x == None:
        return
    inorder(x.l)
    
    global inlist
    inlist.append(x.key)
    
    inorder(x.r)

def insert(root,z):
    y = None
    x = root
    while x != None:
        y = x
        if z.key < x.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 outorder(root):
    x = root
    if x == None:
        return
    global outlist
    outlist.append(x.key)
    
    outorder(x.l)
    outorder(x.r)

for data in treelist:
    if data[0] == "insert":
        z = binaryTree(int(data[1]))
        root = insert(root,z)
        
    if data[0] == "print":
        inlist = []
        outlist = []
        
        inorder(root)
        indata = " " + " ".join([str(num) for num in inlist])
        print(indata)
 
        outorder(root)
        outdata = " " + " ".join([str(num) for num in outist])
        print(outdata)


# Fixed version:
class binaryTree:
    def __init__(self,key,p=None,l=None,r=None):
        self.key = key
        self.p = p
        self.l = l
        self.r = r

N = int(input())
treelist = [list(input().split()) for i in range(N)]
root = None

def inorder(root):
    x = root
    if x == None:
        return
    inorder(x.l)
    
    global inlist
    inlist.append(x.key)
    
    inorder(x.r)

def insert(root,z):
    y = None
    x = root
    while x != None:
        y = x
        if z.key < x.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 outorder(root):
    x = root
    if x == None:
        return
    global outlist
    outlist.append(x.key)
    
    outorder(x.l)
    outorder(x.r)

for data in treelist:
    if data[0] == "insert":
        z = binaryTree(int(data[1]))
        root = insert(root,z)
        
    if data[0] == "print":
        inlist = []
        outlist = []
        
        inorder(root)
        indata = " " + " ".join([str(num) for num in inlist])
        print(indata)
 
        outorder(root)
        outdata = " " + " ".join([str(num) for num in outlist])
        print(outdata)

# Buggy version:
#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]))



# Fixed version:
#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]))
        preParseList = []
        inParseList = []

# Buggy version:
class Node():
    def __init__(self, key):
        self.key = key
        self.left = self.right = None
        
def insert(key):
    global root

    x = root
    y = None
    while x:x, y = x.left if key < x.key else x.right , x
    if y == None:root = Node(key)
    elif y.key < key:y.right = Node(key)
    else:y.left = Node(key)
        
        
def pre(node):
    if node == None:return
    print('',node.key, end = '');pre(node.left);pre(node.right)
    
def ino(node):
    if node == None:return
    ino(node.left);print('',node.key,end='');ino(node.right)


n = int(input())
root = None
for j in range(n):
    s, *i = input().split()
    if s[0] == 'i':insert(int(i[0]))
    else:
        ino(root);print('');pre(root)print()
        
    


# Fixed version:
class Node():
    def __init__(self, key):
        self.key = key
        self.left = self.right = None
        
def insert(key):
    global root

    x = root
    y = None
    while x:x, y = x.left if key < x.key else x.right , x
    if y == None:root = Node(key)
    elif y.key < key:y.right = Node(key)
    else:y.left = Node(key)
        
        
def pre(node):
    if node == None:return
    print('',node.key, end = '');pre(node.left);pre(node.right)
    
def ino(node):
    if node == None:return
    ino(node.left);print('',node.key,end='');ino(node.right)


n = int(input())
root = None
for j in range(n):
    s, *i = input().split()
    if s[0] == 'i':insert(int(i[0]))
    else:
        ino(root);print();pre(root);print()

# Buggy version:
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
        self.p = None
        
        
def insert(root, add):
    parent = None
    pCandidate = root
    while pCandidate is not None:
        parent = pCandidate
        if add.key < pCandidate.key:
            pCandidate = pCandidate.left
        else:
            pCandidate = pCandidate.right
    add.p = parent
    
    if parent is None:
        root = add
    elif add.key < parent.key:
        parent.left = add
    else:
        parent.right = add
    return root

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

n = int(input())
root = None
for i in range(n):
    line = input().split()
    if line[0] == "insert":
        root = insert(root, Node(int(line[1])))
    else:
        inorderTreeWalk(root)
        print()
        preorderTreeWalk(root)
        print()

# Fixed version:
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
        self.p = None
        
        
def insert(root, add):
    parent = None
    pCandidate = root
    while pCandidate is not None:
        parent = pCandidate
        if add.key < pCandidate.key:
            pCandidate = pCandidate.left
        else:
            pCandidate = pCandidate.right
    add.p = parent
    
    if parent is None:
        root = add
    elif add.key < parent.key:
        parent.left = add
    else:
        parent.right = add
    return root

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

n = int(input())
root = None
for i in range(n):
    line = input().split()
    if line[0] == "insert":
        root = insert(root, Node(int(line[1])))
    else:
        inorderTreeWalk(root)
        print()
        preorderTreeWalk(root)
        print()

# Buggy version:
import sys

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

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

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

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

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

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

# Fixed version:
import sys
  
class Node():
    def __init__(self,key):
        self.key = key
        self.left = None
        self.right = None
  
def insert(t, z):
    y = None
    x = t
    while x is not None:
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right
  
    if y is None:
        return z
    else:
        if z.key < y.key:
            y.left = z
        else:
            y.right = z
        return t
  
def inorder(t):
    s = ""
    l = []
    curr = t
    while True:
        while curr is not None:
            l.append(curr)
            curr = curr.left
        if curr is None and len(l) == 0:
            break
        else:
            curr = l.pop()
            s += " " + str(curr.key)
            curr = curr.right
    return s
  
def preorder(t):
    s = ""
    l = []
    curr = t
    while True:
        while curr is not None:
            s += " " + str(curr.key)
            l.append(curr)
            curr = curr.left
        if curr is None and len(l) == 0:
            break
        else:
            curr = l.pop()
            curr = curr.right
    return s
  
t = None
n = sys.stdin.readline()
lines = sys.stdin.readlines()
for line in lines:
    com = line.split()
    if com[0] == "insert":
        t = insert(t, Node(int(com[1])))
    else:
        print(inorder(t))
        print(preorder(t))

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

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

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




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

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

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

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

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




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

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

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

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

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

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

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

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

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

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

# Buggy version:
import sys

class Node():
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
        self.parent = 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

    def print(self):
        print('', ' '.join(map(str, self.root.inwalk())))
        print('', ' '.join(map(str, self.root.prewalk())))

class Tree():
    def __init__(self):
        self.root = None
    def insert(self, key):
        Nz = Node(key)
        Ny = None #???????£?
        Nx = self.root
        while Nx:
            Ny = Nx
            if Nz.key < Ny.key:
                Nx = Nx.left
            else:
                Nx = Nx.right

        Nz.parent = Ny
        if Ny == None:
            self.root = Nz
        elif Nz.key < Ny.key:
            Ny.left = Nz
        else:
            Ny.right = Nz

tree = Tree()

n = sys.stdin.readline()
for line in sys.stdin:
    if line[0] == 'i':
        tree.insert(int(line.split()[1]))
    else:
        tree.print()

# Fixed version:
import sys

class Node():
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
        self.parent = 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

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

    def insert(self, key):
        Nz = Node(key)
        Ny = None #???????£?
        Nx = self.root
        while Nx:
            Ny = Nx
            if Nz.key < Ny.key:
                Nx = Nx.left
            else:
                Nx = Nx.right
        Nz.parent = Ny
        if Ny == None:
            self.root = Nz
        elif Nz.key < Ny.key:
            Ny.left = Nz
        else:
            Ny.right = Nz

    def print(self):
        print('', ' '.join(map(str, self.root.inwalk())))
        print('', ' '.join(map(str, self.root.prewalk())))

tree = Tree()

n = sys.stdin.readline()
for line in sys.stdin:
    if line[0] == 'i':
        tree.insert(int(line.split()[1]))
    else:
        tree.print()

# Buggy version:
treeRoot = {'left': None, 'right': None, 'p': None, 'val': None}

root = None


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


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


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


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

# Fixed version:
treeRoot = {'left': None, 'right': None, 'p': None, 'val': None}

root = None


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


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


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


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

# Buggy version:
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()

# Fixed version:
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(" ", end="")
        print(*list(map(str, self.root.inwalk())))
        print(" ", end="")
        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()

# Buggy version:
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)

# Fixed version:
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)

# Buggy version:
#BinarySearchTree
class TreeNode():
    def __init__(self):
        self.key = None
        self.parent = None
        self.left = None
        self.right = None
    def inoder(self):
        r=[]
        if self.left:
            r += self.left.inoder()
        r += [self.key]
        if self.right:
            r += self.right.inoder()
        return r

    def preoder(self):
        r=[self.key]
        if self.left:
            r += self.left.inoder()
        if self.right:
            r += self.right.inoder()
        return r

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

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

    def show(self):
        x = self.root
        print(" " + " ".join(map(str, self.root.inoder())))
        print(" " + " ".join(map(str, self.root.preoder())))
 
 
n = int(input())
Tree = BinaryTree()
for i in range(n):
    L = input().split()
    if L[0] == "insert":
        Node = TreeNode()
        Node.key = int(L[1])
        Tree.insert(Node)
    else:
        Tree.show()

# Fixed version:
#BinarySearchTree
class TreeNode():
    def __init__(self):
        self.key = None
        self.parent = None
        self.left = None
        self.right = None
    def inoder(self):
        r=[]
        if self.left:
            r += self.left.inoder()
        r += [self.key]
        if self.right:
            r += self.right.inoder()
        return r

    def preoder(self):
        r = [self.key]
        if self.left:
            r += self.left.preoder()
        if self.right:
            r += self.right.preoder()
        return r

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

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

    def show(self):
        x = self.root
        print(" " + " ".join(map(str, self.root.inoder())))
        print(" " + " ".join(map(str, self.root.preoder())))
 
 
n = int(input())
Tree = BinaryTree()
for i in range(n):
    L = input().split()
    if L[0] == "insert":
        Node = TreeNode()
        Node.key = int(L[1])
        Tree.insert(Node)
    else:
        Tree.show()

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

class Tree():
    def __init__(self):
        self.root = None
    def insert(self, key):
        z = Node(key)
        y = None
        x = self.root
        while x:
            y = x
            if z.key < x.key:
                x = x.left
            else:
                x = x.right
        z.parent = y
        
        if y == None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z
        
    def preorder(self, node):
        print(" {}".format(node.key), end = "")
        if node.left:
            self.preorder(node.left)
        if node.right:
            self.preorder(node.right)
            
    def inorder(self, node):
        if node.left:
            self.preorder(node.left)
        print(" {}".format(node.key), end = "")
        if node.right:
            self.preorder(node.right)
            
    def out(self):
        self.inorder(self.root)
        print('')
        self.preorder(self.root)
        print('')

tree = Tree()
N = int(input())
for _ in range(N):
    order = input().split()
    if order[0] == 'insert':
        tree.insert(int(order[1]))
    else:
        tree.out()

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

class Tree():
    def __init__(self):
        self.root = None
    def insert(self, key):
        z = Node(key)
        y = None
        x = self.root
        while x:
            y = x
            if z.key < x.key:
                x = x.left
            else:
                x = x.right
        z.parent = y
        
        if y == None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z
        
    def preorder(self, node):
        print(" {}".format(node.key), end = "")
        if node.left:
            self.preorder(node.left)
        if node.right:
            self.preorder(node.right)
            
    def inorder(self, node):
        if node.left:
            self.inorder(node.left)
        print(" {}".format(node.key), end = "")
        if node.right:
            self.inorder(node.right)
            
    def out(self):
        self.inorder(self.root)
        print('')
        self.preorder(self.root)
        print('')

tree = Tree()
N = int(input())
for _ in range(N):
    order = input().split()
    if order[0] == 'insert':
        tree.insert(int(order[1]))
    else:
        tree.out()

# Buggy version:
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)

# Fixed version:
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(" ", end = "")
        print(*a)
        a = []
        bt.preorder(a)
        print(" ", end = "")
        print(*a)

# Buggy version:
import sys

class Node:
    __slots__ = ['key', 'left', 'right']
    def __init__(self, key):
        self.key = key
        self.left = self.right = None

class BST:
    def __init__(self):
        self.root = None
    def insert(self, key):
        x, y = self.root, None
        while x != None: x, y = x.left if key < x.key else x.right, x
        if y == None: self.root = Node(key)
        elif key < y.key: y.left = Node(key)
        else: y.right = z
    def print_tree(self):
        def inorder(node):
            return inorder(node.left) + f' {node.key}' + inorder(node.right) if node else ''
        def preorder(node):
            return f' {node.key}' + preorder(node.left) + preorder(node.right) if node else ''
        print(inorder(self.root))
        print(preorder(self.root))

tree = BST()
input()
for e in sys.stdin:
    if e[0] == 'i': tree.insert(int(e[7:]))
    else: tree.print_tree()


# Fixed version:
import sys

class Node:
    __slots__ = ['key', 'left', 'right']
    def __init__(self, key):
        self.key = key
        self.left = self.right = None

class BST:
    __slots__ = ['root']
    def __init__(self):
        self.root = None
    def insert(self, key):
        x, y = self.root, None
        while x != None: x, y = x.left if key < x.key else x.right, x
        if y == None: self.root = Node(key)
        elif key < y.key: y.left = Node(key)
        else: y.right = Node(key)
    def print_tree(self):
        def inorder(node):
            return inorder(node.left) + f' {node.key}' + inorder(node.right) if node else ''
        def preorder(node):
            return f' {node.key}' + preorder(node.left) + preorder(node.right) if node else ''
        print(inorder(self.root))
        print(preorder(self.root))

tree = BST()
input()
for e in sys.stdin:
    if e[0] == 'i': tree.insert(int(e[7:]))
    else: tree.print_tree()

# Buggy version:
import sys

class Node():
    __slots__ = ['key', 'left', 'right']
    def __init__(self, key):
        self.key = key
        self.left, self.right = None

root = None
def insert(z):
    global root
    x, y = root, None
    while x:
        y = x
        if z < x.key:
            x = x.left
        else:
            x = x.right
    
    if y == -1:
        root = Node(z)
    elif z < y.key:
        y.left = Node(z)
    else:
        y.right = Node(z)
        
def preorder(x):
    return f" {x.key}" + preorder(x.left) + preorder(x.right) if x else ""

def inorder(x):
    return inorder(x.left) + f" {x.key}" + inorder(x.right) if x else ""
        
input()
node = {}
root = -1
for s in sys.stdin:
    if s[0] == "p":
        print(inorder(root))
        print(preorder(root))
    else:
        insert(int(s[7:])



# Fixed version:
import sys

class Node():
    __slots__ = ['key', 'left', 'right']
    def __init__(self, key):
        self.key = key
        self.left, self.right = None, None
        
    def __str__(self):
        return self.key

root = None
def insert(z):
    global root
    x, y = root, None
    while x:
        y = x
        if z < x.key:
            x = x.left
        else:
            x = x.right
    
    if y == None:
        root = Node(z)
    elif z < y.key:
        y.left = Node(z)
    else:
        y.right = Node(z)
        
def preorder(x):
    return f" {x.key}" + preorder(x.left) + preorder(x.right) if x else ""

def inorder(x):
    return inorder(x.left) + f" {x.key}" + inorder(x.right) if x else ""
        
input()
node = {}
for s in sys.stdin:
    if s[0] == "p":
        pass
        print(inorder(root))
        print(preorder(root))
    else:
        insert(int(s[7:]))

# Buggy version:
class Tree:
    def __init__(self, orders):
        self.root = None
        for order in orders:
            if len(order) == 1:
                self.inorder_print()
                self.preorder_print()
            else:
                self.insert(int(order[1]))

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

        if not y:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z

    def inorder_print(self):
        self.root.inorder_print()
        print()

    def preorder_print(self):
        self.root.preorder_print()
        print()


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

    def inorder_print(self):
        if self.left:
            self.left.inorder_print()
        print(' {}'.format(self.key), end='')
        if self.right:
            self.right.inorder_print()

    def preorder_print(self):
        print(' {}'.format(self.key), end='')
        if self.left:
            self.left.preorder_print()
        if self.right:
            self.right.preorder_print()


if __name__ == '__main__':
    import sys
    m = int(input())
    orders = [line.strip().split() for line in sys.stdin]
    # orders = [input().split() for i in range(m)]



# Fixed version:
class Tree:
    def __init__(self, orders):
        self.root = None
        for order in orders:
            if len(order) == 1:
                self.inorder_print()
                self.preorder_print()
            else:
                self.insert(int(order[1]))

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

        if not y:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z

    def inorder_print(self):
        self.root.inorder_print()
        print()

    def preorder_print(self):
        self.root.preorder_print()
        print()


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

    def inorder_print(self):
        if self.left:
            self.left.inorder_print()
        print(' {}'.format(self.key), end='')
        if self.right:
            self.right.inorder_print()

    def preorder_print(self):
        print(' {}'.format(self.key), end='')
        if self.left:
            self.left.preorder_print()
        if self.right:
            self.right.preorder_print()


if __name__ == '__main__':
    import sys
    m = int(input())
    orders = [line.strip().split() for line in sys.stdin]
    # orders = [input().split() for i in range(m)]
    Tree(orders)

# Buggy version:
#coding:utf-8
N = int(input())
trees = [list(input().split()) for i in range(N)]

class BinaryTree:
    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,z):
    y = None
    x = root
    while x != None:
        y = x
        if z.key < x.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 preOrder(root):
    x = root
    if x == None:
        return
    global preList
    preList.append(x.key)
    
    preOrder(x.l)
    preOrder(x.r)

def inOrder(root):
    x = root
    if x == None:
        return
    inOrder(x.l)

    global inList
    inList.append(x.key)
    
    inOrder(x.r)

root = None
for data in trees:
    if data[0] == "insert":
        z = BinaryTree(int(data[1]))
        root = Insert(root,z)
    if data[0] == "print":
        inList = []
        preList = []
        inOrder(root)
        a = " ".join([str(num) for num in inList])
        print(a)

        preOrder(root)
        a = " ".join([str(num) for num in preList])
        print(a)



# Fixed version:
#coding:utf-8
N = int(input())
trees = [list(input().split()) for i in range(N)]

class BinaryTree:
    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,z):
    y = None
    x = root
    while x != None:
        y = x
        if z.key < x.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 preOrder(root):
    x = root
    if x == None:
        return
    global preList
    preList.append(x.key)
    
    preOrder(x.l)
    preOrder(x.r)

def inOrder(root):
    x = root
    if x == None:
        return
    inOrder(x.l)

    global inList
    inList.append(x.key)
    
    inOrder(x.r)

root = None
for data in trees:
    if data[0] == "insert":
        z = BinaryTree(int(data[1]))
        root = Insert(root,z)
    if data[0] == "print":
        inList = []
        preList = []
        inOrder(root)
        a = " " + " ".join([str(num) for num in inList])
        print(a)

        preOrder(root)
        a = " " + " ".join([str(num) for num in preList])
        print(a)