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.

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

    def __repr__(self):
        
        return str(self.key)

def insert(T, z):
    y = None
    x = T 
    while x != None:
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right
    z.p = y
    
    if y == None:
        
        T = z
        print(T)
    elif z.key<y.key:
        
        y.left = z
    else:
        
        y.right = z

def find(T, k, show):
    x = T 
    while x != None:
        if k == x.key:
            if show:
                print('yes')
            return x
        if k < x.key:
            x = x.left
        else:
            x = x.right
    print('no')
    

def getScu(x):
    if x.right == None:
        y = x.p
        while x == y.right and y != None:
            x = y
            y = x.p
        return y
    x = x.right
    while x != None:
        y = x
        x = x.left
    return y




def delete(T,x):
    
    if x.left == x.right == None:
        
        if x.p.key < x.key:
            x.p.right = None
        else:
            x.p.left = None

    elif x.left == None:
        
        y = x.right
        x.key = y.key
        x.right = y.right
        x.left = y.left
        
    elif x.right == None:
        
        y = x.left
        x.key = y.key
        x.right = y.right
        x.left = y.left
        
    else:
        y = getScu(x)
        delete(T, y)
        x.key = y.key



    

def printPreorder(x):
    if x == None:
        return
    printPreorder(x.left)
    print(end=' ')
    print(x,end='')
    printPreorder(x.right)

def printMidorder(x):
    if x == None:
        return
    print(end=' ')
    print(x,end='')
    printMidorder(x.left)
    printMidorder(x.right)

def printal(x):
    printPreorder(x)
    print()
    printMidorder(x)
    print()


N = int(input())
Q = input().split()
T = Node(int(Q[1]),None,None,None)
for i in range(N-1):
    Q = input().split()
    if Q[0] == "print":
        printal(T)
        continue
    elif Q[0] == "find":
        find(T,int(Q[1]),True)
        continue
    elif Q[0] == "delete":
        delete(T,find(T, int(Q[1]), False))
        continue
    insert(T,Node(int(Q[1]),None,None,None))

Solution (Python):
'''
def delete(z):
    global root
    if TL[z] == NIL or TR[z] == NIL:
        y = z
    else:
        y = get_next(z)
    if TL[y] != NIL:
        x = TL[y]
    else:
        x = TR[y]
    if x != NIL:
        TP[x] = TP[y]
    if TP[y] == NIL:
        root = x
    elif y == TL[TP[y]]:
        TL[TP[y]] = x
    else:
        TR[TP[y]] = x
    if y != z:
        TP[z], TR[z], TL[z] = TP[y], TR[y], TL[y]
    del TP[y]
    del TR[y]
    del TL[y]
    print(z)
    hyouzi()

    
    
    
    if TR[x] == NIL and TL[x] == NIL:
        if TR[TP[x]] == x:
            TR[TP[x]] = NIL
        else:
            TL[TP[x]] = NIL
    elif TR[x] == NIL:
        if TR[TP[x]] == x:
            TR[TP[x]] = TL[x]
            TP[TL[x]] = TP[x]
        else:
            TL[TP[x]] = TL[x]
            TP[TL[x]] = TP[x]
    elif TL[x] == NIL:
        if TR[TP[x]] == x:
            TR[TP[x]] = TR[x]
            TP[TR[x]] = TP[x]
        else:
            TL[TP[x]] = TR[x]
            TP[TR[x]] = TP[x]
    else:
        y = get_next(x)
        TP[x], TR[x], TL[x] = TP[y], TR[y], TL[y]
        delete(y)
'''


def insert(z):
    global root
    y = NIL
    x = root
    
    while x != NIL:
        y = x
        if z < x:
            x = TL[x]
        else:
            x = TR[x]
    TP[z] = y

    if y == NIL:
        root = z
    elif z < y:
        TL[y] = z
    else:
        TR[y] = z


def inorder(u):
    if u == NIL:
        return
    inorder(TL[u])
    print(' ', end='')
    print(u, end='')
    inorder(TR[u])


def preorder(v):
    if v == NIL:
        return
    print(' ', end='')
    print(v, end='')
    preorder(TL[v])
    preorder(TR[v])


def get_next(x):
    if TR[x] != NIL:
        return get_minimum(TR[x])
    y = TP[x]
    while y != NIL and x == TR[y]:
        x = y
        y = TP[y]
    return y


def get_minimum(x):
    while TL[x] != NIL:
        x = TL[x]
    return x


def treedelete(z):
    if z in TL:
        if TL[z] != NIL and TR[z] != NIL:
            y = get_next(z)
            '''
            print(y, z)
            print(TR)
            print(TL)
            print(TP)
            '''
        else:
            y = z
        if TL[y] == NIL and TR[y] == NIL:
            if TR[TP[y]] == y:
                TR[TP[y]] = NIL
            else:
                TL[TP[y]] = NIL
        elif TL[y] == NIL and TR[y] != NIL:
            if TR[TP[y]] == y:
                TR[TP[y]] = TR[y]
                TP[TR[y]] = TP[y]
            else:
                TL[TP[y]] = TR[y]
                TP[TR[y]] = TP[y]
        elif TL[y] != NIL and TR[y] == NIL:
            if TR[TP[y]] == y:
                TR[TP[y]] = TL[y]
                TP[TL[y]] = TP[y]
            else:
                TL[TP[y]] = TL[y]
                TP[TL[y]] = TP[y]
        if y != z:
            if TR[TP[z]] == z:
                TR[TP[z]] = y
            else:
                TL[TP[z]] = y
            TP[TL[z]] = y
            TP[TR[z]] = y
            TL[y], TR[y], TP[y] = TL[z], TR[z], TP[z]
            del TL[z], TR[z], TP[z]
            
            
        else:
            del TL[y], TR[y], TP[y]



def hyouzi():
    inorder(root)
    print()
    preorder(root)
    print()


TR = {}
TL = {}
TP = {}
NIL = 10000000000000000000000
root = NIL
m = int(input())
data = [input().split() for _ in range(m)]

for i in data:
    if i[0][0] == 'i':
        TR[int(i[1])] = TL[int(i[1])] = NIL
        insert(int(i[1]))
    elif i[0][0] == 'f':
        if int(i[1]) in TR:
            print('yes')
        else:
            print('no')
    elif i[0][0] == 'd':
        
        treedelete(int(i[1]))
    elif i[0][0] == 'p':
        hyouzi()
    '''
    print(i)
    print(TR)
    print(TL)
    print(TP)
    '''

Solution (Python):

class Node:

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


def input_line() -> (str, int):
    line = input().split()
    if line[0] == 'print':
        return line[0], None
    else:
        return line[0], int(line[1])


def preorder(tree: Node) -> None:
    """先行順巡回。"""
    print(f' {tree.key}', end='')
    if tree.left is not None:
        preorder(tree.left)
    if tree.right is not None:
        preorder(tree.right)


def inorder(tree: Node) -> None:
    """中間順巡回。"""
    if tree.left is not None:
        inorder(tree.left)
    print(f' {tree.key}', end='')
    if tree.right is not None:
        inorder(tree.right)


def do_inorder(node: Node) -> Node:
    if node.left is not None:
        return do_inorder(node.left)
    return node
    if node.right is not None:
        return inorder(node.right)


def get_next_node(node: Node) -> Node:
    """inorderで次の節点を返す。"""
    next_node = do_inorder(node.right)
    return next_node


def insert(new_node: Node) -> None:
    """二分探索木に挿入する。"""

    
    global root

    
    parent = None

    
    tmp = root

    
    while tmp is not None:
        parent = tmp
        if new_node.key < tmp.key:
            tmp = tmp.left
        else:
            tmp = tmp.right

    
    new_node.parent = parent

    
    if parent is None:
        
        root = new_node
    elif new_node.key < parent.key:
        parent.left = new_node
    else:
        parent.right = new_node


def find(key)-> bool:
    if get_node(key) is None:
        return False
    else:
        return True


def get_node(key: int) -> Node:
    """キーが一致するノードを返す。"""
    global root

    
    node = root

    
    while node is not None:
        if key == node.key:
            return node
        elif key < node.key:
            node = node.left
        else:
            node = node.right

    return None


def count_child(node: Node) -> int:
    """ノードの子供の数を取得する。"""
    child_num = 0
    if node.left is not None:
        child_num += 1
    if node.right is not None:
        child_num += 1
    return child_num


def do_delete(node: Node) -> None:
    
    if node is None:
        return

    child_num = count_child(node)
    parent = node.parent

    if parent is None:
        raise ValueError('親がないケース')

    
    
    if child_num == 0:
        if parent.left is not None and parent.left.key == node.key:
            parent.left = None
        
        else:
            parent.right = None

    
    elif child_num == 1:
        if parent.left is not None and parent.left.key == node.key:
            if node.left is not None:
                parent.left = node.left
                parent.left.parent = parent
            else:
                parent.left = node.right
                parent.left.parent = parent
        else:
            if node.left is not None:
                parent.right = node.left
                parent.right.parent = parent
            else:
                parent.right = node.right
                parent.right.parent = parent

    
    elif child_num == 2:
        
        next_node = get_next_node(node)
        node.key = next_node.key
        do_delete(next_node)
    else:
        raise ValueError('想定してない事態')


def delete(key: int) -> None:

    node = get_node(key)
    do_delete(node)


root = None  
N = int(input())
for _i in range(N):
    order, val = input_line()
    if order == 'insert':
        node = Node(val)
        insert(node)
    elif order == 'print':
        inorder(root)
        print()
        preorder(root)
        print()
    elif order == 'find':
        if find(val):
            print('yes')
        else:
            print('no')
    elif order == 'delete':
        delete(val)

Solution (Python):
import sys


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

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

    def replace(self, child, new_child):
        if child is self.left:
            self.left = new_child
        else:
            self.right = new_child
        if new_child:
            new_child.parent = self

    def __str__(self):
        return f'({str(self.left or "_")} {self.key} {str(self.right or "_")})'


def insert(root, z):
    if root is None:
        return z

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

    z.parent = y

    if z.key < y.key:
        y.left = z
    else:
        y.right = z

    return root


def find(node, key):
    while node and node.key != key:
        if key < node.key:
            node = node.left
        elif key > node.key:
            node = node.right
    return node


def next_node(node):
    while node.left:
        node = node.left
    return node


def delete(root, key):
    node = find(root, key)
    if not node:
        return root
    if node is root:
        return None

    delete_node(node)
    return root


def delete_node(node):
    if not node.left and not node.right:
        node.parent.replace(node, None)
    elif node.left and node.right:
        next = next_node(node.right)
        node.key = next.key
        delete_node(next)
    else:  
        node.parent.replace(node, node.left or node.right)


def inorder(node):
    if not node:
        return
    yield from inorder(node.left)
    yield node.key
    yield from inorder(node.right)


def preorder(node):
    if not node:
        return
    yield node.key
    yield from preorder(node.left)
    yield from preorder(node.right)


def print_tree(root):
    print(''.join(' ' + str(key) for key in inorder(root)))
    print(''.join(' ' + str(key) for key in preorder(root)))


root = None

n = int(sys.stdin.readline())
for _ in range(n):
    command, *args = sys.stdin.readline().split()
    if command == 'insert':
        root = insert(root, Node(int(args[0])))
    elif command == 'find':
        print('yes' if find(root, int(args[0])) else 'no')
    elif command == 'delete':
        root = delete(root, int(args[0]))
    else:
        print_tree(root)

Solution (Python):




import sys
input = sys.stdin.readline
import cProfile

class node:
    def __init__(self,nodeid):
        self.parent = None
        self.c_left = None
        self.c_right = None
        self.nodeid = nodeid
    def setChild(self,n,cn=None):
        if (cn == None):
            cn = self
        if ( cn.nodeid < n):
            if (cn.c_right == None):
                cn.c_right = node(n) 
                cn.c_right.parent =  cn 
                return cn.c_right
            else:
                return self.setChild(n,cn.c_right)
        else:
            if (cn.c_left == None):
                cn.c_left = node(n) 
                cn.c_left.parent =  cn
                return cn.c_left 
            else:
                return self.setChild(n,cn.c_left)

    def getPreorder(self,r1=[]):
        r1.append(self.nodeid)
        if (self.c_left != None):
            r1 = self.c_left.getPreorder(r1)
        if (self.c_right != None):
            r1 = self.c_right.getPreorder(r1)
        return r1       
    def getInorder(self,r1=[]):
        if (self.c_left != None):
            r1 = self.c_left.getInorder(r1)
        r1.append(self.nodeid)
        if (self.c_right != None):
            r1 = self.c_right.getInorder(r1)
        return r1       
    def getPostorder(self,r1=[]):
        if (self.c_left != None):
            r1 = self.c_left.getPostorder(r1)
        if (self.c_right != None):
            r1 = self.c_right.getPostorder(r1)
        r1.append(self.nodeid)
        return r1       
    def find(self,n):
        if self.nodeid == n:
            return True
        if self.nodeid > n:
            if (self.c_left == None ):
                return False
            return self.c_left.find(n)
        else:
            if  (self.c_right == None):
                return False
            return self.c_right.find(n)

    def findObject(self,n):
        if self.nodeid == n:
            return self
        if self.nodeid > n:
            if (self.c_left == None ):
                return None
            return self.c_left.findObject(n)
        else:
            if  (self.c_right == None):
                return None
            return self.c_right.findObject(n)

    def deleteNum(self,n):
        i = self.findObject(int(n))
        if i == None:
            return False
        self.deleteObject(i)
        return True

    def deleteObject(self,obj):
        p = obj.parent
        x = obj
        if x.c_left == None and x.c_right == None:
            if p.c_right.nodeid == x.nodeid:
                p.c_right = None
            else:
                p.c_left = None
            x.nodeid = -1
            x.parent = None
            x.c_right = None
            x.c_left = None
            return

        if x.c_left == None and x.c_right != None:
            if p.c_right != None and p.c_right.nodeid == obj.nodeid:
                p.c_right = x.c_right
                x.c_right.parent = p
            else:
                p.c_left = x.c_right
                x.c_right.parent = p
            x.nodeid = -1
            x.parent = None
            x.c_right = None
            x.c_left = None
            return

        if x.c_left != None and x.c_right == None:
            if p.c_right.nodeid == x.nodeid:
                p.c_right = x.c_left
                x.c_left.parent = p
            else:
                p.c_left = x.c_left
                x.c_left.parent = p
            x.nodeid = -1
            x.parent = None
            x.c_right = None
            x.c_left = None
            return

        y = self.findMinObject(x.c_right)
        x.nodeid = y.nodeid
        p = y.parent
        x = y
        if x.c_left == None and x.c_right == None:
            if p.c_right != None and p.c_right.nodeid == x.nodeid:
                p.c_right = None
            else:
                p.c_left = None
            x.nodeid = -1
            x.parent = None
            x.c_right = None
            x.c_left = None
            return

        if x.c_left == None and x.c_right != None:
            if p.c_right.nodeid == obj.nodeid:
                p.c_right = x.c_right
                x.c_right.parent = p
            else:
                p.c_left = x.c_right
                x.c_right.parent = p
            x.nodeid = -1
            x.parent = None
            x.c_right = None
            x.c_left = None
            return

    def findMinObject(self,obj):
        i = obj
        while i != None and i.c_left != None:
            i = i.c_left
        return i

    
    def getRoot(self):
        if (self.parent == None):
            return self
        return self.parent.getRoot()

def printNodeList(nodelist,caption):
    for i in nodelist:
        a = b = c = None
        if (i != None ):
            a = i.nodeid
        if (i.c_left != None):
            b = i.c_left.nodeid
        if (i.c_right != None):
            c = i.c_right.nodeid 
        if ( a != None and (b != None or c != None)):
            print (caption,a,b,c)
            
def main():
    n = int(input())
    nodelist = []
    root = None
    for i in range(n):
        l = list(map(str,input().split()))
        if (l[0] == "print" and root != None):
            print("",*root.getInorder([]))
            print("",*root.getPreorder([]))
        elif (l[0] == "insert"):
            d = int(l[1])
            if ( root == None):
                root = node(d)
                nodelist.append(root)
            else:
                
                nodelist.append(root.setChild(d))
        elif (l[0] == "find"):
            d = int(l[1])
            r = root.find(d)
            if (r == True):
                print ("yes")
            else:
                print ("no")
        elif (l[0] == "delete"):
            
            root.deleteNum(l[1])
            

        
if __name__ == '__main__':
    main()

Solution (Python):
import sys

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

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

    def __repr__(self):
        return "({},{},{},{})".format(self.key, self.parent, self.left, self.right)

    def is_root(self):
        return self.parent is None

    def is_leaf(self):
        return self.left is None and self.right is None

    def has_one_child(self):
        if self.is_leaf():
            return False
        elif (self.left is None) and (self.right is not None):
            return self.right
        elif (self.left is not None) and (self.right is None):
            return self.left
        else:
            return False

    def has_two_child(self):
        return (self.left is not None) and (self.right is not None)


root_node_no = None

def insert(nodes :dict, in_node :Node):
    global root_node_no

    cur_node_no = root_node_no
    parent_node_no = None
    while cur_node_no is not None:
        parent_node_no = cur_node_no
        if in_node.key < cur_node_no:
            cur_node_no = nodes[cur_node_no].left
        else:
            cur_node_no = nodes[cur_node_no].right

    in_node.parent = parent_node_no

    if root_node_no is None:
        root_node_no = in_node.key
    elif in_node.key < parent_node_no:
        nodes[parent_node_no].left = in_node.key
    else:
        nodes[parent_node_no].right = in_node.key

    nodes[in_node.key] = in_node

def inorder_tree_walk(nodes, node_no ,inorder):
    if node_no is None:
        return
    inorder_tree_walk(nodes, nodes[node_no].left, inorder)
    inorder.append(node_no)
    inorder_tree_walk(nodes, nodes[node_no].right, inorder)

def preorder_tree_walk(nodes, node_no, preorder):
    if node_no is None:
        return
    preorder.append(node_no)
    preorder_tree_walk(nodes, nodes[node_no].left, preorder)
    preorder_tree_walk(nodes, nodes[node_no].right, preorder)


def find(nodes, tgt_node_no):
    cur_node_no = root_node_no
    while cur_node_no is not None:
        cur_node = nodes[cur_node_no]
        if cur_node.key == tgt_node_no:
            return True
        elif tgt_node_no < cur_node.key:
            cur_node_no = cur_node.left
        else:
            cur_node_no = cur_node.right
    return False


def switch_child_of_parent(nodes: dict, del_node: Node, switch_node_no):
    if nodes[del_node.parent].left == del_node.key:
        nodes[del_node.parent].left = switch_node_no
    elif nodes[del_node.parent].right == del_node.key:
        nodes[del_node.parent].right = switch_node_no
    return


def delete_node(nodes: dict, delete_node_no: int):
    del_node = nodes[delete_node_no]

    if del_node.is_leaf():
        
        switch_child_of_parent(nodes, del_node, None)
    elif not del_node.has_two_child():
        
        child = del_node.has_one_child()
        switch_child_of_parent(nodes, del_node, child)
        nodes[child].parent = del_node.parent
    else:
        
        inorder = []
        inorder_tree_walk(nodes, del_node.right, inorder)
        swap_node = Node(inorder[0])
        switch_child_of_parent(nodes, del_node, swap_node.key)

        swap_node.parent = del_node.parent
        swap_node.left = del_node.left
        if swap_node.key == del_node.right:
            swap_node.right = None
        else:
            swap_node.right = del_node.right
            nodes[swap_node.right].parent = swap_node.key
        nodes[swap_node.left].parent = swap_node.key
        delete_node(nodes, swap_node.key)
        nodes[swap_node.key] = swap_node

    del nodes[delete_node_no]
    return


def main():
    num_com = int(input())
    commands = sys.stdin.readlines()
    nodes = {}
    for i in range(num_com):
        if commands[i][0] == 'i':
            insert(nodes, Node(int(commands[i][7:])))
        elif commands[i][0] == 'p':
            
            inorder = []
            inorder_tree_walk(nodes, root_node_no, inorder)
            print(" " + " ".join(map(str, inorder)))
            
            preorder = []
            preorder_tree_walk(nodes, root_node_no, preorder)
            print(" " + " ".join(map(str, preorder)))
        elif commands[i][0] == 'f':
            if find(nodes, int(commands[i][5:])):
                print('yes')
            else:
                print('no')
        elif commands[i][0] == 'd':
            delete_node(nodes, int(commands[i][7:]))

main()

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


def insert(root,node):
    if(root.key <= node.key):
        if(root.right is None):
            root.right=node
            node.parent=root
        else:
            insert(root.right,node)
    
    else:
        if(root.left is None):
            root.left=node
            node.parent=root
        else:
            insert(root.left,node)


def find(root,key):
    if(root.key==key):
        return root

    elif(root.key < key):
        if(root.right is not None):
            return find(root.right,key)
        else:
            return None

    else:
        if(root.left is not None):
            return find(root.left,key)
        else:
            return None






def delete(Root,key):
    root=Root[0]
    target=find(root,key)
    if(target is None):
        pass

    elif(target.parent is None):
        return 0



    else:
        parent=target.parent

        if(parent.key <= target.key):
            right=1
        else:
            right=0
        

        if((target.left is None) and (target.right is None)):
            if(right):
                parent.right=None
            else:
                parent.left=None

        elif(target.left is None):
            target.right.parent=parent
            if(right):
                parent.right=target.right
            else:
                parent.left=target.right

        elif(target.right is None):
            target.left.parent=parent
            if(right):
                parent.right=target.left
            else:
                parent.left=target.left
        
        else:
            tmp_min=target.right
            while(tmp_min.left is not None):
                tmp_min=tmp_min.left
            
            if(tmp_min.parent.key <=tmp_min.key):
                if(right):
                    parent.right=tmp_min
                else:
                    parent.left=tmp_min
                tmp_min.parent=parent
                tmp_min.left=target.left
                target.left.parent=tmp_min
                return 1
            
            if(tmp_min.right is not None):
                tmp_min.parent.left=tmp_min.right
                tmp_min.right.parent=tmp_min.parent
            
            tmp_min.parent.left=None
            tmp_min.left=target.left
            target.left.parent=tmp_min
            tmp_min.right=target.right
            target.right.parent=tmp_min
            tmp_min.parent=parent
            if(right):
                parent.right=tmp_min
            else:
                parent.left=tmp_min
    return 1

                   
            
        



    

def Preorder(root,order):
    order.append(root.key)
    if(root.left is not None):
        Preorder(root.left,order)
    
    if(root.right is not None):
        Preorder(root.right,order)




def Inorder(root,order):
    if(root.left is not None):
        Inorder(root.left,order)
    
    order.append(root.key)


    if(root.right is not None):
        Inorder(root.right,order)




n=int(input())



root=None


for loop in range(n):
    ope=input().split()

    if(ope[0]=="insert"):
        tmp_node=Node(int(ope[1]))
        try:
            insert(root,tmp_node)
        except:
            root=tmp_node
    
    elif(ope[0]=="find"):
        try:
            if(find(root,int(ope[1])) is not None):
                print("yes")

            else:
                print("no")
        except:
            print("no")
    
    elif(ope[0]=="delete"):
        Root=[root]
        if(delete(Root,int(ope[1])) ==0):
            root=None

    else:
        in_order=[]
        p_order=[]

        
        Inorder(root,in_order)
        Preorder(root,p_order)

        for x in in_order:
            print(f" {x}",end="")
            
        print()
        for x in p_order:
            print(f" {x}",end="")
        print()

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

root = None
def insert(z):
    global root
    y = None
    x = root
    while x:
        y = x
        x = x[z[2] >= x[2]]
    z[3] = y

    if not y:
        root = z
    else:
        y.__setitem__(z[2] >= y[2], z)

def find(k):
    x = root
    while x:
        if x[2] == k:
            return 1
        x = x[k >= x[2]]
    return 0

def __delete(x):
    global root
    if x[0] and x[1]:
        y = x[1]
        while y[0]:
            y = y[0]
        x[2] = y[2]
        __delete(y)
    elif not x[0] and not x[1]:
        if x[3]:
            p = x[3]
            p.__setitem__(p[1] is x, None)
        else:
            root = None
        del x
    else:
        y = x[0] or x[1]

        if x[3]:
            p = x[3]

            y[3] = p
            p[p[1] is x] = y
        else:
            y[3] = None
            root = y
        del x

def delete(k):
    x = root
    while x:
        if x[2] == k:
            break
        x = x[k >= x[2]]
    if not x:
        return
    __delete(x)

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

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


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