Problem:

Binary Search Tree III

Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II.

  
insert  $k$: Insert a node containing $k$ as key into $T$.

  
find $k$: Report whether $T$ has a node containing $k$. 

  
delete $k$: Delete a node containing $k$.

  
print: Print the keys of the binary search tree by inorder tree walk and  preorder tree walk respectively.

The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases:

 If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$).

 If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent.

 If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key.

Input

   In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given.

Output

For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not.

  In addition, 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

18
insert 8
insert 2
insert 3
insert 7
insert 22
insert 1
find 1
find 2
find 3
find 4
find 5
find 6
find 7
find 8
print
delete 3
delete 7
print

Sample Output 1

yes
yes
yes
no
no
no
yes
yes
 1 2 3 7 8 22
 8 2 1 3 7 22
 1 2 8 22
 8 2 1 22

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.



Sample input:
18
insert 8
insert 2
insert 3
insert 7
insert 22
insert 1
find 1
find 2
find 3
find 4
find 5
find 6
find 7
find 8
print
delete 3
delete 7
print


Sample output:
yes
yes
yes
no
no
no
yes
yes
 1 2 3 7 8 22
 8 2 1 3 7 22
 1 2 8 22
 8 2 1 22

Submission status: Accepted

Solution code:
n = int(input())
inst_k = [-1]*n
inst = [-1]*n
for i in range(n):
    tmp = input().split()
    inst[i] = tmp[0]
    if len(tmp) == 2:
        inst_k[i] = int(tmp[1])

class BST:
    def __init__(self):
        self.key = []
        self.parent = []
        self.left_child = []
        self.right_child = []
        self.root = None

    def insert(self,new_key):
        new_node = len(self.key)
        self.key.append(new_key)
        self.left_child.append(None)
        self.right_child.append(None)
        self.parent.append(None)

        searching_node = self.root
        searching_node_parent = None
        while searching_node != None:
            searching_node_parent = searching_node
            if new_key < self.key[searching_node]:
                searching_node = self.left_child[searching_node]
            else:
                searching_node = self.right_child[searching_node]
        if searching_node_parent == None:
            self.root = new_node
        else:
            self.parent[new_node] = searching_node_parent
            if new_key < self.key[searching_node_parent]:
                self.left_child[searching_node_parent] = new_node
            else:
                self.right_child[searching_node_parent] = new_node
    
    def print_clear(self):
        self.preorder_ans = []
        self.inorder_ans = []
    
    def preorder(self,node):
        if node != None:
            self.preorder_ans.append(self.key[node])
            self.preorder(self.left_child[node])
            self.preorder(self.right_child[node])
    
    def inorder(self,node):
        if node != None:
            self.inorder(self.left_child[node])
            self.inorder_ans.append(self.key[node])
            self.inorder(self.right_child[node])
    
    def find(self,key,node):
        if node == None:
            return None
        else:
            if self.key[node] == key:
                return node
            else:
                if key < self.key[node]:
                    return self.find(key,self.left_child[node])
                else:
                    return self.find(key,self.right_child[node])
     
    def delete(self,key):
        del_node = self.find(key,self.root)
        if self.left_child[del_node] == None or self.right_child[del_node] == None:
            instead_node = del_node
        else:
            instead_node = self.getSuccessor(del_node)
        
        if self.left_child[instead_node] != None:
            instead_node_child = self.left_child[instead_node]
        else:
            instead_node_child = self.right_child[instead_node]
        
        if instead_node_child != None:
            self.parent[instead_node_child] = self.parent[instead_node]

        if self.root == instead_node:
            self.root = instead_node_child
        elif self.left_child[self.parent[instead_node]] == instead_node:
            self.left_child[self.parent[instead_node]] = instead_node_child
        else:
            self.right_child[self.parent[instead_node]] = instead_node_child
        
        if instead_node != del_node:
            self.key[del_node] = self.key[instead_node]



    def getSuccessor(self,node):
        if self.right_child[node] != None:
            return self.getMinimum(self.right_child[node])
        else:
            ret = node
            while self.left_child[self.parent[ret]] != ret and ret != None:
                ret = self.parent[ret]
            return self.parent[ret]
    
    def getMinimum(self,node):
        while self.left_child[node] != None:
            node = self.left_child[node]
        return node
        
        

            



tree = BST()
for i in range(n):
    if inst[i] == "insert":
        tree.insert(inst_k[i])

    elif inst[i] == "find":
        if tree.find(inst_k[i],tree.root) != None:
            print("yes")
        else:
            print("no")

    elif inst[i] == "delete":
        tree.delete(inst_k[i])

    elif inst[i] == "print":
        tree.print_clear()
        tree.preorder(tree.root)
        tree.inorder(tree.root)
        print(" ",end = "")
        print(*tree.inorder_ans)
        print(" ",end = "")
        print(*tree.preorder_ans)

Submission status: Accepted

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

class BST:
    def __init__(self):
        self.root = None
    
    def insert(self, key):
        x, y = self.root, None
        z = Node()
        z.key = key
        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 find(self, key):
        r = self.root
        while r != None:
            if key == r.key:
                break
            elif key < r.key:
                r = r.left
            else:
                r = r.right
        return r
    
    def delete(self, key, r = -1):
        if r == -1:
            r = self.root
        if r == None:
            return None
        if r.key == key:
            if r.left == r.right == None:
                p = r.parent
                if p == None:
                    self.root = None
                    return None
                return None
            elif r.left != None and r.right != None:
                s = self.successor(r)
                r.key = s.key
                r.right = self.delete(s.key, r.right)
                return r
            elif r.left != None:
                p = r.parent
                if p == None:
                    self.root =r.left
                    r.left.p = None
                    return r.left
                if p.left == r:
                    p.left = r.left
                    r.left.parent = p
                else:
                    p.right = r.left
                    r.left.parent = p
                return r.left
            elif r.right != None:
                p = r.parent
                if p == None:
                    self.root = r.right
                    r.right.p = None
                    return r.right
                if p.left == r:
                    p.left = r.right
                    r.right.parent = p
                else:
                    p.right = r.right
                    r.right.parent = p
                return r.right
        elif r.key < key:
            r.right = self.delete(key, r.right)
        else:
            r.left = self.delete(key, r.left)
        return r

    def successor(self, r):
        r = r.right
        if r == None:
            return None
        while r.left != None:
            r = r.left
        return r
    
    def preOrder(self, r = -1):
        if r == -1: r = self.root
        if r == None:   return
        print("", r.key, end = '')
        self.preOrder(r.left)
        self.preOrder(r.right)
    
    def inOrder(self, r = -1):
        if r == -1: r = self.root
        if r == None:   return
        self.inOrder(r.left)
        print("", r.key, end = '')
        self.inOrder(r.right)

tree = BST()
for _ in range(int(input())):
    s = input()
    if s[0] == 'i':
        tree.insert(int(s[7:]))
    elif s[0] == 'p':
        tree.inOrder()
        print("")
        tree.preOrder()
        print("")
    elif s[0] == 'f':
        print(['no', 'yes'][tree.find(int(s[5:])) != None])
    else:
        tree.delete(int(s[7:]))

Submission status: Accepted

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

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

T = {}
root = None

def insert_node(key):
    global root
    x = root
    y = None
    z = Node(None, None, None)
    while x != None:
        y = x
        if key < x:
            x = T[x].left
        else:
            x = T[x].right
    z.parent = y
    if y == None:
        root = key
    else:
        if key < y:
            T[y].left = key
        else:
            T[y].right = key
    T[key] = z

def find_node(key):
    x = root
    while x != None and key != x:
        if key < x:
            x = T[x].left
        else:
            x = T[x].right
    if x != None:
        print('yes')
    else:
        print('no')

def get_minimum(key):
    while T[key].left != None:
        key = T[key].left
    return key

def delete_node(key):
    global root
    parent = T[key].parent

    if T[key].left == None and T[key].right == None:
        if T[parent].left == key:
            T[parent].left = None
        elif T[parent].right == key:
            T[parent].right = None
        del T[key]

    elif T[key].right == None:
        key_is_left = True if T[parent].left == key else False
        child = T[key].left
        if key_is_left:
            T[parent].left = child
        else:
            T[parent].right = child
        T[child].parent = parent
        del T[key]

    elif T[key].left == None:
        key_is_left = True if T[parent].left == key else False
        child = T[key].right
        if key_is_left:
            T[parent].left = child
        else:
            T[parent].right = child
        T[child].parent = parent
        del T[key]

    elif T[key].left != None and T[key].right != None:
        left, right = T[key].left, T[key].right
        node_next_more = get_minimum(T[key].right)
        next_more_right = T[node_next_more].right
        next_more_parent = T[node_next_more].parent
        if parent == None:
            if node_next_more == right:
                T[right].parent = None
                T[right].left = left
                root = right
                del T[key]
                return
            else:
                T[node_next_more].left = left
                T[node_next_more].right = right
                T[node_next_more].parent = None
                T[left].parent = node_next_more
                T[right].parent = node_next_more
                if next_more_right != None:
                    T[next_more_right].parent = next_more_parent
                root = node_next_more
                del T[key]
                return
        else:
            key_is_left = True if T[parent].left == key else False
            if node_next_more == right:
                if key_is_left:
                    T[parent].left = right
                else:
                    T[parent].right = right
                T[right].parent = parent
                T[right].left = left
                del T[key]
                return
            else:
                if key_is_left:
                    T[parent].left = node_next_more
                else:
                    T[parent].right = node_next_more
                T[node_next_more].left = T[key].left
                T[node_next_more].right = T[key].right
                T[node_next_more].parent = parent
                T[left].parent = node_next_more
                T[right].parent = 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[key]
                return

def in_print(key, ls):
    if key == None:
        return
    in_print(T[key].left, ls)
    ls.append(key)
    in_print(T[key].right, ls)

def pre_print(key, ls):
    if key == None:
        return
    ls.append(key)
    pre_print(T[key].left, ls)
    pre_print(T[key].right, ls)

def print_node():
    in_ls, pre_ls = [], []
    in_print(root, in_ls)
    pre_print(root, pre_ls)
    print('', *in_ls)
    print('', *pre_ls)

N = int(input())
for i in range(N):
    com = input().split()
    if com[0] == 'insert':
        insert_node(int(com[1]))
    elif com[0] == 'find':
        find_node(int(com[1]))
    elif com[0] == 'delete':
        delete_node(int(com[1]))
    elif com[0] == 'print':
        print_node()

Submission status: Accepted

Solution code:
class Node:
    def __init__(self):
        self.key = -1
        self.p = -1
        self.l = -1
        self.r = -1

def insert(k):
    y = -1
    x = root[0]
    z = len(T)
    T.append(Node())
    T[z].key = k
    while x != -1:
        y = x
        if T[z].key < T[x].key: x = T[x].l
        else: x = T[x].r
    T[z].p = y
    if y == -1: root[0] = z
    elif T[z].key < T[y].key: T[y].l = z
    else: T[y].r = z

def find(k):
    x = root[0]
    while x != -1 and T[x].key != k:
        if k < T[x].key: x = T[x].l
        else: x = T[x].r
    return x

def delete(z):
    if T[z].l == -1 or T[z].r == -1: y = z
    else: y = getSuccessor(z)
    if T[y].l != -1: x = T[y].l
    else: x = T[y].r
    if x != -1: T[x].p = T[y].p
    if T[y].p == -1: root[0] = x
    elif y == T[T[y].p].l: T[T[y].p].l = x
    else: T[T[y].p].r = x
    if y != z: T[z].key = T[y].key

def getSuccessor(x):
    if T[x].r != -1: return getMinimum(T[x].r)
    y = T[x].p 
    while y != -1 and x == T[y].r:
        x = y
        y = T[y].p
    return y

def getMinimum(x):
    while T[x].l != -1: x = T[x].l
    return x

def inorder(u):
    if u == -1: return
    inorder(T[u].l)
    print(" {}".format(T[u].key),end="")
    inorder(T[u].r)

def preorder(u):
    if u == -1: return
    print(" {}".format(T[u].key),end="")
    preorder(T[u].l)
    preorder(T[u].r)

m = int(input())
T = []
root = [-1]
lst = [input().split() for _ in range(m)]
for i in range(m):
    comm = lst[i][0]
    if len(lst[i]) == 2: key = int(lst[i][1])
    if comm == "insert":
        insert(key)
    elif comm == "find":
        print("yes" if find(key) != -1 else "no")
    elif comm == "delete":
        delete(find(key))
    else:
        inorder(root[0])
        print("")
        preorder(root[0])
        print("")

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

root = None

def insert(key):
    global root
    x,y = root,None
    while x:
        y = x
        x = x.left if key < x.key else x.right
    if y is None:root = Node(key)
    elif key < y.key:y.left = Node(key)
    else:y.right = Node(key)

def find(target):
    result = root
    while result and target != result.key:
        result = result.left if target < result.key else result.right
    return result is None

def delete(target):
    def remove_node(p,c,a):
        if p.left == c: p.left = a
        else: p.right = a
    p,c = None,root
    while c.key != target:
        p,c = c,c.left if target < c.key else c.right
    if c.left is None:
        remove_node(p,c,c.right)
    elif c.right is None:
        remove_node(p,c,c.left)
    elif c.right.left is None:
        c.right.left = c.left#親の上書き
        remove_node(p,c,c.right)
    else:
        g = c.right
        while g.left.left:g = g.left
        c.key = g.left.key
        g.left = g.left.right

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 ""

input()
for e in sys.stdin:
    if e[0] == "i":insert(int(e[7:]))
    elif e[0] =="d":delete(int(e[7:]))
    elif e[0] =="f":print(["yes","no"][find(int(e[5:]))])
    else:print(inorder(root));print(preorder(root))

Submission status: Accepted

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

class Tree(object):
    def __init__(self):
        self.root = None
        self.value_dic = {}
    
    def is_find(self,value):
        if value in self.value_dic:
            return True
        else:
            return False
    
    def find(self,value):
        node = T.root

        while node :
            if value == node.value:
                break
            elif value > node.value:
                node = node.right
            else :
                node = node.left
        return node

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

    T.value_dic[z.value] = 1

def getMinimum(z):
    while z.left != None:
        z = z.left
    return z

def getSuccessor(z):
    if z.right != None:
        return getMinimum(z.right)

    y = z.parent
    while y != None and z == y.right:
        z = y
        y = y.parent
    return y

def delete(T,z):
    # 削除する対象をyとする
    if z.left is None or z.right is None:
        y = z
    else:
        y = getSuccessor(z)

    # 子をxとする
    if y.left != None:
        x = y.left
    else:
        x = y.right
    

    # 子がいる場合
    if x != None:
        x.parent = y.parent
    
    if y.parent is None:
        T.root = x
    elif y.parent.left == y:
        y.parent.left = x
    else:
        y.parent.right = x
    
    if y != z:
        z.value = y.value



# 先行順巡回
def preorder(node):
    if node is None:
        return 
    print(" "+str(node.value),end="")    
    preorder(node.left)
    preorder(node.right)
    
# 中間順巡回 
def inorder(node):
    if node is None:
        return 
    inorder(node.left)
    print(" "+str(node.value),end="")
    inorder(node.right)
    
def print_all_node(root):
    stack = [root]
    while stack:
        node = stack.pop()
        print("p: ",node.parent,"r:",node.right,"l:",node.left)
        if node.left:
            stack.append(node.left)
        if node.right:
            stack.append(node.right)

if __name__ == "__main__":
    n = int(input())
    T = Tree()
    queries = [input().split() for _ in range(n)]
    for query in queries:
        if query[0] == "print":
            #print_all_node(T.root)
            inorder(T.root)
            print("")
            preorder(T.root)
            print("")

        else:
            command,value = query
            if command == "insert":
                node_z = Node()
                node_z.value = int(value)
                insert(T,node_z)
            elif command == "find":
                if T.is_find(int(value)):
                    print("yes")
                else:
                    print("no")
            elif command == "delete":
                node = T.find(int(value))
                if node:
                    T.value_dic.pop(int(value))
                delete(T,node)

Submission status: Accepted

Solution code:
# Binary Search Tree 3

import sys
sys.setrecursionlimit(10**6)


class Node():
    __slots__ = ['key', 'parent', 'left', 'right']

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

    def __repr__(self):
        k = str(self.key)
        p = str(self.parent.key) if self.parent else 'None'
        l = str(self.left.key) if self.left else 'None'
        r = str(self.right.key) if self.right else 'None'
        s = "<Node %s: parent=%s, left=%s, right=%s>" % (k, p, l, r)
        return s


class BinaryTree():
    def __init__(self, n=0):
        self.T = [Node() for _ in range(n)]
        self.root = None

    def preorder(self):
        self.preorder_key = []
        self.preorder_rec(self.root)
        print('', *(self.preorder_key))

    def preorder_rec(self, node):
        if node == None:
            return
        self.preorder_key.append(node.key)
        self.preorder_rec(node.left)
        self.preorder_rec(node.right)

    def inorder(self):
        self.inorder_key = []
        self.inorder_rec(self.root)
        print('', *(self.inorder_key))

    def inorder_rec(self, node):
        if node == None:
            return
        self.inorder_rec(node.left)
        self.inorder_key.append(node.key)
        self.inorder_rec(node.right)

    def insert(self, key):
        node = Node(key)

        y = None
        x = self.root

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

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

    def find(self, x, key):
        while x != None and key != x.key:
            if key < x.key:
                x = x.left
            else:
                x = x.right
        return x

    def has(self, key):
        if self.find(self.root, key) != None:
            return True
        else:
            return False

    def get_successor(self, x):
        # 次節点
        if x.right != None:
            return self.get_minimum(x.right)

        y = x.parent
        while y != None and x == y.right:
            x, y = y, y.parent
        return y

    def get_minimum(self, x):
        # xを根とする部分木のうち最小のキーを持つノードを返す
        while x.left != None:
            x = x.left
        return x

    def delete(self, key):
        # 削除
        z = self.find(self.root, key)
        if z.left != None and z.right != None:
            y = self.get_successor(z)
            z.key = y.key
        else:
            y = z

        # 子xを決める
        x = y.left if y.left != None else y.right
        if x != None:
            x.parent = y.parent

        if y.parent == None:  # 根のとき
            self.root = x
        elif y == y.parent.left:
            y.parent.left = x
        else:
            y.parent.right = x


N = int(input())
S = [input() for _ in range(N)]
tree = BinaryTree()

for s in S:
    if 'print' in s:
        tree.inorder()
        tree.preorder()
    else:
        command, key = s.split()
        key = int(key)

        if 'find' in command:
            print('yes' if tree.has(key) else 'no')

        if 'delete' in command:
            tree.delete(key)

        elif 'insert' in command:
            tree.insert(key)

Submission status: Accepted

Solution code:
import sys
n = int(input())
class Node:
  def __init__(self,v):
    self.p = None
    self.key = v
    self.left = None
    self.right = None

sys.setrecursionlimit(15000)
r = None
def insert(z):
  global r
  y = None
  x = r
  while x != None:
    y = x
    if z.key < x.key:
      x = x.left
    else:
      x = x.right
  z.p = y

  if y == None:
    r = z
  elif z.key < y.key:
    y.left = z
  else:
    y.right = z

ret = []
def inorder(r):
  if r == None: return
  inorder(r.left)
  ret.append(r.key)
  inorder(r.right)

def preorder(r):
  if r == None: return
  ret.append(r.key)
  preorder(r.left)
  preorder(r.right)

def search(r,key):
  if r == None: return None
  if r.key == key:
    return r
  if r.key < key:
    return search(r.right,key)
  else:
    return search(r.left,key)

def delete(key):
  global r
  z = search(r,key)
  if not z.left or not z.right:
    y = z # node to delete
  else:
    y = z.right
    while y.left:
      y = y.left

  if y.left:
    x = y.left # child node of delete node
  else:
    x = y.right

  if x:
    x.p = y.p

  if y.p == None:
    r = x
  elif y == y.p.left:
    y.p.left = x
  else:
    y.p.right = x

  if y != z:
    z.key = y.key

for i in range(n):
  s = input()
  #print(s)
  if s[0]=="i":
    insert(Node(int(s.split()[1])))
  elif s[0]=="f":
    if search(r,int(s.split()[1])) != None:
      print("yes")
    else:
      print("no")
  elif s[0]=="d":
    #print("d",int(s.split()[1]))
    #print(r.key)
    delete(int(s.split()[1]))
  else:
    #print("p")
    ret = []
    inorder(r)
    print(""," ".join(map(str,ret)))
    ret = []
    preorder(r)
    print(""," ".join(map(str,ret)))

Submission status: Accepted

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

root = 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 find(key):
    
    x = root
    answer = None

    while x != None:

        if key == x.key:
            answer = x
            break

        if key < x.key:
            x = x.left
        else:
            x = x.right
    
    return answer
    
def delete(key):
    z = find(key)

    if z.left == None and z.right == None:
        if key < z.parent.key:
            z.parent.left = None
        else:
            z.parent.right = None
    
    elif z.left != None and z.right == None :
        if z.key < z.parent.key:
            z.parent.left = z.left
        else:
            z.parent.right = z.left
        
        z.left.parent = z.parent
    
    elif z.left == None and z.right != None :
        if z.key < z.parent.key:
            z.parent.left = z.right
        else:
            z.parent.right = z.right
        
        z.right.parent = z.parent

    elif z.left != None and z.right != None:
        next_node = z.right

        while next_node.left != None:
            next_node = next_node.left

        new_key = next_node.key
        delete(new_key)

        z.key = new_key

def Inorder_TreeWalk(node):
    if node is None:
        return

    Inorder_TreeWalk(node.left)
    print(" " + str(node.key), end="")
    Inorder_TreeWalk(node.right)

def Preorder_TreeWalk(node):
    if node is None:
            return
            
    print(" " + str(node.key), end="")
    Preorder_TreeWalk(node.left)
    Preorder_TreeWalk(node.right)

def Main():
    global root
    n = int(input())
    
    for i in range(n):
        inp = input().split()
        ope = inp[0]

        if ope == "insert":
            insert(node(int(inp[1]), None, None, None))
        
        elif ope == "find":
            target = find(int(inp[1]))

            if target != None:
                print("yes")
            else:
                print("no")

        elif ope == "delete":
            delete(int(inp[1]))

        elif ope == "print":
            Inorder_TreeWalk(root)
            print()
            Preorder_TreeWalk(root)
            print()
Main()