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:
# coding: utf-8

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

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

    def find(self, key):
        y = None
        x = self.root
        while True:
            if x.me == key:
                return x
            elif x.me > key:
                if x.left != None:
                    x = x.left
                else:
                    return None
            else:
                if x.right != None:
                    x = x.right
                else:
                    return None
    
    def delete(self, key):
        z = self.find(key)
        if z.left == None and z.right == None:
            if z.parent.left == z:
                z.parent.left = None
            else:
                z.parent.right = None
        elif z.left != None and z.right == None:
            if z.parent.left == z:
                z.parent.left = z.left
                z.left.parent = z.parent
            if z.parent.right == z:
                z.parent.right = z.left
                z.left.parent = z.parent
        elif z.left == None and z.right != None:
            if z.parent.left == z:
                z.parent.left = z.right
                z.right.parent = z.parent
            if z.parent.right == z:
                z.parent.right = z.right
                z.right.parent = z.parent
        else:
            #y = nextPos(z) # z.right.left.left....の最下層
            y = z.right
            while y.left != None:
                y = y.left
            p = y.me
            self.delete(y.me)
            z.me = p
            
    def getPreorder(self, node, ans):
        ans.append(node)
        if node.left != None:
            self.getPreorder(node.left, ans)
        if node.right != None:
            self.getPreorder(node.right, ans)
            
    def getInorder(self, node, ans):
        if node.left != None:
            self.getInorder(node.left, ans)
        ans.append(node)
        if node.right != None:
            self.getInorder(node.right, ans)

        
def printAns(ans):
    for a in ans:
        print(" " + str(a.me),end="")
    print()
    
m = int(input().rstrip())
nt = NodeTree()
for i in range(m):
    line = input().rstrip().split()
    if line[0] == "insert":
        nt.insert(Node(int(line[1]),None,None))
    elif line[0] == "find":
        if nt.find(int(line[1])) != None:
            print("yes")
        else:
            print("no")
    elif line[0] == "delete":
        nt.delete(int(line[1]))
    else:
        ans = []
        nt.getInorder(nt.root,ans)
        printAns(ans)
        ans = []
        nt.getPreorder(nt.root,ans)
        printAns(ans)

Submission status: Accepted

Solution code:
err = 2*(10**9)+1

class STNode:
    def __init__(self, k, l, r, p):
        self.key = k
        self.left = l
        self.right = r
        self.parent = p

def STinsert(h, z):
    global err
    p = None
    while True:
        if h.key == err:
            break
        p = h
        if z.key < h.key:
            h = h.left
        else:
            h = h.right
    if z.key < p.key:
        p.left = z
    else:
        p.right = z
    z.parent = p

def STsearch(h, k):
    global err
    while h.key != err:
        if k < h.key:
            h = h.left
        elif h.key < k:
            h = h.right
        else:
            return h
    return None

def STdelete(head, k):
    global err
    h = STsearch(head, k)
    if h is None:
        pass
    else:
        if h.left.key == err and h.right.key == err:
            if k < h.parent.key: #h.leftはNULLnode
                h.parent.left = h.left
            else:
                h.parent.right = h.left
        elif h.left.key == err: #right child exists
            h.right.parent = h.parent
            if k < h.parent.key: #h.leftはNULLnode
                h.parent.left = h.right
            else:
                h.parent.right = h.right
        elif h.right.key == err: #left child exists
            h.left.parent = h.parent
            if k < h.parent.key: #h.rightはNULLnode
                h.parent.left = h.left
            else:
                h.parent.right = h.left
        else:
            #一度右の子に移りそこから限界まで左の子を見る
            #左の子がNULLnodeならループを抜ける
            #その節点の子が0個か1個かにより処理を分ける
            temp = h.right
            flg = 0 #一度でもwhile内部で左の子に移動したら1
            while temp.left.key != err:
                temp = temp.left
                flg = 1

            #tempは中間順でhの次節点を参照する
            h.key = temp.key
            if temp.right.key == err:
                if flg == 1:
                    temp.parent.left = temp.left
                else:
                    temp.parent.right = temp.left
            else:
                temp.right.parent = temp.parent
                if flg == 1:
                    temp.parent.left = temp.right
                else:
                    temp.parent.right = temp.right


def preorder(head, h, A):
    global err
    if h.key == err:
        return
    A.append(h.key)
    preorder(head, h.left, A)
    preorder(head, h.right, A)
    if head == h:
        print('', *A)

def inorder(head, h, B):
    global err
    if h.key == err:
        return
    inorder(head, h.left, B)
    B.append(h.key)
    inorder(head, h.right, B)
    if head == h:
        print('', *B)

n = int(input())
NULLnode = STNode(err, None, None, None)

first = list(input().split())
head = STNode(int(first[1]), NULLnode, NULLnode, NULLnode)

for i in range(n-1):
    temp = list(input().split())
    if temp[0] == "insert":
        z = STNode(int(temp[1]), NULLnode, NULLnode, NULLnode)
        STinsert(head, z)
    elif temp[0] == "print":
        A = []
        B = []
        inorder(head, head, B)
        preorder(head, head, A)
    elif temp[0] == "find":
        res = STsearch(head, int(temp[1]))
        if res is None:
            print("no")
        else:
            print("yes")
    else: #delete
        STdelete(head, int(temp[1]))

Submission status: Accepted

Solution code:
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) + "[" + str(self.p)+"]"
        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
    #print(x,y,z)
    if y == None:
        #print("Y==None")
        T = z
        print(T)
    elif z.key<y.key:
        #print("z.key<y.key")
        y.left = z
    else:
        #print("z.key<y.key")
        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):
    #print(x.key, id(x))
    if x.left == x.right == None:
        #print("x.left == x.right == None")
        if x.p.key < x.key:
            x.p.right = None
        else:
            x.p.left = None

    elif x.left == None:
        #print("x.left == None")
        y = x.right
        x.key = y.key
        x.right = y.right
        x.left = y.left
        #print(x.key, id(x))
    elif x.right == None:
        #print("x.right == None")
        y = x.left
        x.key = y.key
        x.right = y.right
        x.left = y.left
        #print(x.key, id(x))
    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))

Submission status: Accepted

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

    #print(TR)
    #print(TL)
    #print(x)
    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
    #print(x)
    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]
            #print(TL[z], TR[z], TP[z], TL[y], TR[y], TP[y])
            #TL[z], TR[z], TP[z] = TL[y], TR[y], TP[y]
        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)]
#print(data)
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':
        #print(i[1])
        treedelete(int(i[1]))
    elif i[0][0] == 'p':
        hyouzi()
    '''
    print(i)
    print(TR)
    print(TL)
    print(TP)
    '''

Submission status: Accepted

Solution code:

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:
    """二分探索木に挿入する。"""

    # rootはglobalに共有する。
    global root

    # new_nodeを付け加える節(parent)の初期値をNoneに設定する。
    parent = None

    # tmpにrootを設定する。
    tmp = root

    # new_nodeを付け加える節(parent)を探索する。
    while tmp is not None:
        parent = tmp
        if new_node.key < tmp.key:
            tmp = tmp.left
        else:
            tmp = tmp.right

    # new_nodeの親を設定する。
    new_node.parent = parent

    # new_nodeの子供を設定する。
    if parent is None:
        # treeが空だった場合は、rootにnew_nodeを設定する。
        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

    # tmpにrootを設定する。
    node = root

    # new_nodeを付け加える節(parent)を探索する。
    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:
    # delete対象がない場合はメソッドを終了する。
    if node is None:
        return

    child_num = count_child(node)
    parent = node.parent

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

    # keyに一致するノードをzとおく。
    # パターン1: zが子を持たない場合。
    if child_num == 0:
        if parent.left is not None and parent.left.key == node.key:
            parent.left = None
        # if parent.right is not None and parent.right.key == node.key:
        else:
            parent.right = None

    # パターン2: zが子をひとつ持つ場合。
    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

    # パターン3: zが子をふたつ持つ場合。
    elif child_num == 2:
        # inorderでnodeの次に出る節点を取得する。
        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  # treeの根を表す。初期値は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)

Submission status: Accepted

Solution code:
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.left xor node.right
        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)

Submission status: Accepted

Solution code:
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_8_C&lang=jp
# Binary Search Tree III python3
# 2018.11.27 yonezawa

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:
                #root.setChild(d)
                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"):
            #printNodeList(nodelist,"Debug:rm "+str(l[1])+":")
            root.deleteNum(l[1])
            #printNodeList(nodelist,"Debug:post rm "+str(l[1])+":")

        
if __name__ == '__main__':
    main()
    #pr = cProfile.Profile()
    #pr.runcall(main)
    #pr.print_stats()