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: Accepted

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 insert(node):
    global root
    y = None
    x = root
    while x is not None:
        y = x
        if node.value < x.value:
            x = x.left
        else:
            x = x.right
    node.parent = y
    if y is None:
        root = node
    elif node.value < y.value:
        y.left = node
    else:
        y.right = 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]))
        insert(Node(int(val[0])))
    elif cmd == "print":
        print("", *inorder_walk(root))
        print("", *preorder_walk(root))

Submission status: Accepted

Solution code:
import sys


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

        def has_left(self):
            return self.left is not None

        def has_right(self):
            return self.right is not None

        def __str__(self):
            return str(self.value)

    def __init__(self):
        self.root = None

    def insert(self, value):
        if self.root is None:
            self.root = self.Node(value)
            return

        node = self.root
        while True:
            if node.value > value:
                if node.has_left():
                    node = node.left
                else:
                    node.left = self.Node(value)
                    break
            else:
                if node.has_right():
                    node = node.right
                else:
                    node.right = self.Node(value)
                    break

    def preorder(self):
        def _preorder(node):
            yield node
            if node.has_left():
                yield from _preorder(node.left)
            if node.has_right():
                yield from _preorder(node.right)
        if self.root is not None:
            yield from _preorder(self.root)

    def inorder(self):
        def _inorder(node):
            if node.has_left():
                yield from _inorder(node.left)
            yield node
            if node.has_right():
                yield from _inorder(node.right)
        if self.root is not None:
            yield from _inorder(self.root)

    def postorder(self):
        def _postorder(node):
            if node.has_left():
                yield from _postorder(node.left)
            if node.has_right():
                yield from _postorder(node.right)
            yield node
        if self.root is not None:
            yield from _postorder(self.root)


def run():
    _ = int(input())
    tree = BinarySearchTree()

    for line in sys.stdin:
        command = line.split()
        if command[0] == 'insert':
            tree.insert(int(command[1]))
        elif command[0] == 'print':
            inorder = ''
            for node in tree.inorder():
                inorder += " {}".format(node)
            print(inorder)
            preorder = ''
            for node in tree.preorder():
                preorder += " {}".format(node)
            print(preorder)
        else:
            raise ValueError('invalid command')


if __name__ == '__main__':
    run()

Submission status: Accepted

Solution code:
import copy
class Node():
    def __init__(self, parent = -1, left = -1, right = -1):
        self.parent = parent
        self.left = left
        self.right = right
        
    def __eq__(self, other):
        if self.num == other.num:
            return True
        else:
            return False

def insert(node, z):
    global root
    p = -1
    x = root
    while x != -1:
        p = x
        if z < x:
            x = node[x].left
        else:
            x = node[x].right
    
    if p == -1:
        root = z
        node[z] = Node()
    elif z < p:
        node[p].left = z
        node[z] = Node(p)
    else:
        node[p].right = z
        node[z] = Node(p)
        
def preorder(node, i):
    print(" " + str(i), end ="")
    if node[i].left != -1:
        preorder(node, node[i].left)
    if node[i].right != -1:
        preorder(node, node[i].right)

def inorder(node, i):
    if node[i].left != -1:
        inorder(node, node[i].left)
    print(" " + str(i), end ="")
    if node[i].right != -1:
        inorder(node, node[i].right)
        
n = int(input())
node = {}
root = -1
for i in range(n):
    s = input()
    if s == "print":
        inorder(node, root)
        print()
        preorder(node, root)
        print()
    else:
        s = s.split()
        insert(node, int(s[1]))

Submission status: Accepted

Solution code:
import sys

class Node():
    def __init__(self, parent = -1, left = -1, right = -1):
        self.parent = parent
        self.left = left
        self.right = right
        
    def __eq__(self, other):
        if self.num == other.num:
            return True
        else:
            return False

def insert(node, z):
    global root
    p = -1
    x = root
    while x != -1:
        p = x
        if z < x:
            x = node[x].left
        else:
            x = node[x].right
    
    if p == -1:
        root = z
        node[z] = Node()
    elif z < p:
        node[p].left = z
        node[z] = Node(p)
    else:
        node[p].right = z
        node[z] = Node(p)
        
def preorder(node, i):
    print(" " + str(i), end ="")
    if node[i].left != -1:
        preorder(node, node[i].left)
    if node[i].right != -1:
        preorder(node, node[i].right)

def inorder(node, i):
    if node[i].left != -1:
        inorder(node, node[i].left)
    print(" " + str(i), end ="")
    if node[i].right != -1:
        inorder(node, node[i].right)
        
input()
node = {}
root = -1
for s in sys.stdin:
    if s[0] == "p":
        inorder(node, root)
        print()
        preorder(node, root)
        print()
    else:
        insert(node, int(s[7:]))

Submission status: Accepted

Solution code:
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:]))

Submission status: Accepted

Solution code:
class BinaryTreeNode():
    # __slots__ = ['left', 'right', 'val']
    def __init__(self, left=None, right=None, val=None):
        self.left = left
        self.right = right
        self.val = val

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

    def insert(self, val):
        y = None
        x = self.root
        while x != None:
            y = x
            if val < x.val:
                x = x.left
            else:
                x = x.right
        node = BinaryTreeNode(val=val)

        if y == None:
            self.root = node
        elif node.val < y.val:
            y.left = node
        else:
            y.right = node

    def preorder(self):
        self.preorder_list = []
        self.preorder_bfs(self.root)
        return self.preorder_list

    def preorder_bfs(self, u):
        if u == None: return
        self.preorder_list.append(u.val)
        self.preorder_bfs(u.left)
        self.preorder_bfs(u.right)

    def inorder(self):
        self.inorder_list = []
        self.inorder_dfs(self.root)
        return self.inorder_list

    def inorder_dfs(self, u):
        if u == None: return
        self.inorder_dfs(u.left)
        self.inorder_list.append(u.val)
        self.inorder_dfs(u.right)

def print_elements(arr):
    print(' ' + ' '.join([str(item) for item in arr]))

m = int(input())
bst = BinarySearchTree()
for i in range(m):
    op = input()
    if op == 'print':
        print_elements(bst.inorder())
        print_elements(bst.preorder())
    else:
        num = int(op[7:])
        bst.insert(num)

Submission status: Accepted

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


def insert(t, z):
    x, y = t, -1
    while x != -1:
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right
    z.parent = y

    if y == -1:
        t = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z

    return t


def print_tree(t):
    def in_order(z):
        if z == -1:
            return

        in_order(z.left)
        print(" {}".format(z.key), end="")
        in_order(z.right)

    def pre_order(z):
        if z == -1:
            return

        print(" {}".format(z.key), end="")
        pre_order(z.left)
        pre_order(z.right)

    in_order(t)
    print()
    pre_order(t)
    print()


def main():
    n = int(input())
    bst = -1

    for i in range(n):
        order = input().split()
        if order[0][0] == "i":
            node = Node(key=int(order[1]))
            bst = insert(bst, node)
        else:
            print_tree(bst)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

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

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

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

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

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

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

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

def find(id,root_node):
    node = root_node
    while node.id is not None:
        if id < node.id:
            node = node.left
        elif id > node.id:
            node = node.right
        else:
            print('yes')
            break
    else:
        print('no')

def delete(id, root_node):
    # 作成中
    global null_node
    type = ''
    node = root_node
    node_parent = null_node
    while node.id != id:
        node_parent = node
        if id < node.id:
            node = node.left
            type = 'L'
        else:
            node = node.right
            type = 'R'
    if node.right is not None:
        node.right.parent = node_parent
    elif node.left is not None:
        node.left.parent = node_parent
    else:
        node.parent = null_node

    if type == 'L':
        node_parent.left = null_node
    else:
        node_parent.right = null_node

import sys
# import cProfile
# import pstats
# c_profile = cProfile.Profile()
# c_profile.enable()


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

    elif command == 'find':
        id = int(input_line[1])
        find(id, root_node)

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


# c_profile.disable()
# c_stats = pstats.Stats(c_profile)
# c_stats.sort_stats('tottime').print_stats(10)

Submission status: Accepted

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

    def preorder(self):
        ret = [self.key]
        if self.left:
            ret += self.left.preorder()
        if self.right:
            ret += self.right.preorder()
        return ret

    def inorder(self):
        ret = []
        if self.left:
            ret += self.left.inorder()
        ret += [self.key]
        if self.right:
            ret += self.right.inorder()
        return ret


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

    def insert(self, k):
        z = Node(k)
        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 is None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z

    def print(self):
        print('', ' '.join(map(str, self.root.inorder())))
        print('', ' '.join(map(str, self.root.preorder())))


m = int(input())
tree = Tree()
for _ in range(m):
    s = input().split()
    if s[0] == "insert":
        tree.insert(int(s[1]))
    else:
        tree.print()

Submission status: Accepted

Solution code:
#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)

Submission status: Accepted

Solution code:
import sys

tree={}
np = -1

home=0
tree[home]=[None, None, None]

def search(p, x):
    while p != None:
        tmp = tree[p]
        if tmp[0] == x: return True
        if x < tmp[0]:
            p = tmp[1]
        else:
            p = tmp[2]
    return False

def node(x):
    global np
    np += 1
    tree[np] = [x, None, None]
    return np

def insert(p, x):
    if p == None or np == -1: return node(x)
    tmp = tree[p]
    if x== tmp[0]: return p
    elif x<tmp[0]:
        tree[p][1]=insert(tmp[1],x)
    else:
        tree[p][2]=insert(tmp[2],x)
    return p

def preorder(p):
    if p == None: return []
    p1, p2 = tree[p][1:3]
    return [tree[p][0]] + preorder(p1) + preorder(p2)

def inorder(p):
    if p == None: return []
    p1, p2 = tree[p][1:3]
    return inorder(p1) + [tree[p][0]] +inorder(p2)

n = int(input())
i = 0
while i<n:
    s = raw_input()
    if s[0]=='i':
        insert(0,int(s[7:]))
    elif s[0]=='p':
        print ' ' + ' '.join(map(str, inorder(home)))
        print ' ' + ' '.join(map(str, preorder(home)))
    i += 1

Submission status: Accepted

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin


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


def tree_insert(top, z):
    y = None
    x = top
    while isinstance(x, Node):
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right
    z.parent = y
    if y is None:
        top = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z
    return top


def inorder_walk(node):
    if node.left:
        inorder_walk(node.left)
    print('', node.key, end='')
    if node.right:
        inorder_walk(node.right)


def preorder_walk(node):
    print('', node.key, end='')
    if node.left:
        preorder_walk(node.left)
    if node.right:
        preorder_walk(node.right)


n = int(stdin.readline())
#assert n <= 500000

top = None
for _ in range(n):
    cmd = stdin.readline()
    if cmd.startswith('i'):
        key = int(cmd[7:])
        #assert -2000000000 <= key <= 2000000000
        top = tree_insert(top, Node(key))
    else:
        inorder_walk(top)
        print()
        preorder_walk(top)
        print()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2**20)

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

def pre_parse(T: dict, u: int, pre_ls: list):
    if u is 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: dict, u: int, in_ls: list):
    if u is 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: dict, ROOT: int , z: int):
    if ROOT == z:
        T[z] = Node()
    else:
        T[z] = Node()
        x = ROOT
        while x is not None: #子ノードがNoneになったらbreak
            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 find(T: dict, ROOT: int, k: int):
    """
    Tからkを見つけ出す。見つからなかったらNoneを返す
    """
    x = ROOT
    while x is not None and x != k:
        if k < x:
            x = T[x].left
        else:
            x = T[x].right
    return x

def delete_node(T: dict, z: int):
    # 1. zが子を持たない場合
    parent = T[z].parent
    if (T[z].left is None) and (T[z].right is None):
        # zを削除
        if T[parent].left == z:
            T[parent].left = None
        elif T[parent].right == z:
            T[parent].right = None
        else:
            raise ValueError
        del T[z]
    
    # 2. zがちょうど1つの子を持つ場合
    elif T[z].right is None:
        # 左だけ子がある場合
        is_z_left = True if T[parent].left == z else False
        child = T[z].left
        if is_z_left: # zが、zの親の左側の子なら
            T[parent].left = child
        else: # zが、zの親の右側の子なら
            T[parent].right = child
        T[child].parent = parent
        del T[z]
    
    elif T[z].left is None:
        # 右だけ子がある場合
        is_z_left = True if T[parent].left == z else False
        child = T[z].right
        if is_z_left: # zが、zの親の左側の子なら
            T[parent].left = child
        else: # zが、zの親の右側の子なら
            T[parent].right = child
        T[child].parent = parent
        del T[z]
    
    elif (T[z].left is not None) and (T[z].right is not None):
        left, right = T[z].left, T[z].right
        # 指定したノードの子孫の中で最も小さいノードを返す
        node_next_more = get_min_descendants(T, T[z].right)
        next_more_right = T[node_next_more].right
        next_more_parent = T[node_next_more].parent
        # z がROOTだったら
        if parent is None:
            if node_next_more == right:
                T[right].parent = None
                T[right].left = left
                ROOT = right
                del T[z]
                return
            else:
                # node_next_moreがもっと下にある場合
                T[node_next_more].left = left
                T[node_next_more].right = right
                T[node_next_more].parent = None
                T[left].parent = node_next_more # zの左側の子の親
                T[right].parent = node_next_more # zの右側の子の親
                # node_next_moreの親 -> node_next_more右子の接続
                T[next_more_parent].left = next_more_right
                if next_more_right is not None:
                    T[next_more_right].parent = next_more_parent
                
                del T[z]
                return
        
        else: # zが非ROOTだったら
            is_z_left = True if T[parent].left == z else False
            if node_next_more == right:
                # zをつぶしてzの(元)親の子の枠のうち、もともとｚがいた方に、zの右子を繋げる
                if is_z_left:
                    T[parent].left = right
                else:
                    T[parent].right = right
                T[right].parent = parent
                T[right].left = left
                del T[z]
                return
            else:
                # zの親->next_more
                if is_z_left:
                    T[parent].left = node_next_more
                else:
                    T[parent].right = node_next_more
                # next_more -> z の子
                T[node_next_more].left = left
                T[node_next_more].right = right
                T[node_next_more].parent = parent
                T[left].parent = node_next_more # ｚの左の接続
                T[right].parent = node_next_more # zの右の接続
                # node_next_moreの親 -> node_next_more右子の接続
                # (node_next_moreの親から見ると左に接続される)
                # next_moreはzの親と子の間に繋ぎ変えたので、
                # next_more_parentとnext_more_rightを繋げる。
                T[next_more_parent].left = next_more_right
                if next_more_right is not None:
                    # next_moreの右子があるなら、next_moreの分だけ詰める
                    T[next_more_right].parent = next_more_parent
                
                del T[z]
                return

def get_min_descendants(T:dict, z:int):
    x = z
    while T[x].left is not None:
        x = T[x].left
    return x

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

def main():
    N = int(input())
    T = {}
    ROOT = 0
    for i in range(N):
        tmp = input().split()
        if tmp[0] == "insert":
            value = int(tmp[1])
            if i==0:
                ROOT = value
            insert(T, ROOT, value)
        elif tmp[0] == "find":
            value = int(tmp[1])
            if find(T, ROOT, value):
                print("yes")
            else:
                print("no")
        elif tmp[0] == "delete":
            value = int(tmp[1])
            delete_node(T, value)
        else:
            print_result(T, ROOT)

main()