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:
import sys, collections
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = 10**10
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

class Node():
    key = None
    p = None
    left = None
    right = None

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

class BinarySearchTree():
    root = None

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

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

    def find(self, k):
        x = self.root
        while x is not None:
            if x.key==k:
                return x
            elif x.key>k:
                x = x.left
            else:
                x = x.right
        return None

    def next_node(self, z):
        if z.right is None:
            x = z
            y = z.p
            while y is not None and y.left!=x:
                x = y
                y = y.p
            # print(z.key, y.key)
            return y
        else:
            x = z.right
            while x is not None:
                y = x
                x = x.left
            return y

    def delete(self, k):
        z = self.find(k)
        if z.left is None and z.right is None:
            if z.p.key > z.key:
                z.p.left = None
            else:
                z.p.right = None
        elif z.left is not None and z.right is not None:
            y = self.next_node(z)
            tmp = y.key
            self.delete(y.key)
            z.key = tmp
        else:
            if z.right is None:
                z_child = z.left
            else:
                z_child = z.right
            z_child.p = z.p
            if z.p.key > z.key:
                z.p.left = z_child
            else:
                z.p.right = z_child
            
    def print_nodes(self):
        inorder = []
        preorder = []

        def dfs(v):
            v_key = v.key
            preorder.append(v_key)
            if v.left is not None:
                dfs(v.left)
            inorder.append(v_key)
            if v.right is not None:
                dfs(v.right)

        dfs(self.root)

        print('', *inorder)
        print('', *preorder)

def resolve():
    m = I()
    T = BinarySearchTree()
    for _ in range(m):
        q = LSS()
        if q[0]=='insert':
            k = int(q[1])
            z = Node(k)
            T.insert(z)
        elif q[0]=='find':
            k = int(q[1])
            if T.find(k):
                print('yes')
            else:
                print('no')
        elif q[0]=='delete':
            k = int(q[1])
            T.delete(k)
        else:
            T.print_nodes()
    # print(T.next_node(T.find(1)).key)
    # print(T.next_node(T.find(2)).key)
    # print(T.next_node(T.find(3)).key)
    # print(T.next_node(T.find(7)).key)
    # print(T.next_node(T.find(8)).key)
    # print(T.next_node(T.find(22)).key)

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2**20)  # 再帰回数上限の向上 かなり多くしないとREになる


class Node:
    def __init__(self,
                 parent=None,
                 left=None,
                 right=None):
        self.parent = parent
        self.left = left  # 左の子ノード
        self.right = right  # 右の**子**


def pre_parse(T: dict, u: int, pre_ls: list):
    # 深さ優先探索特有の即時終了条件
    if u == 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, u, in_ls):
    if u == 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, ROOT, z):
    '''
    zは接点番号(そしてその接点番号が内容でもある)
    この接点番号を二分探索木の条件に従うように挿入する。
    '''
    # もしTが空だった場合(最初の一回しか発動されない)
    if ROOT == z:
        T[z] = Node()
    # もしTにいくつか入っていた場合
    else:
        T[z] = Node()  # 初期化
        x = ROOT
        while x is not None:  # 子がNoneになったらbreakする
            next_parent = x  # 次のループではxの親になる。whileから抜けたときに使用する
            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, ROOT, k):
    '''
    Tからkを見つけ出す。見つからなかったらNoneを返す
    ひたすらkの大きさによって左右のパスをたどっていくだけ
    (いま辞書でノードを管理しているので、`k in T.keys()`で済むことではあるんだけど(オーダーは大きくなる)))
    '''
    x = ROOT  # 訪問中のノード
    while x is not None and x != k:
        if k < x:
            x = T[x].left
        else:
            x = T[x].right
    return x

#P219 program 9.3がイマイチ理解できなかったが、仕組みはわかったのでオレオレ実装です
def delete_node(T, z):
    # case1 指定したzが子を持たない場合
    parent = T[z].parent
    if (T[z].left is None) and (T[z].right is None):
        # そのノードを削除する
        if T[parent].left == z:
            T[parent].left = None
        elif T[parent].right == z:
            T[parent].right = None
        else:
            raise ValueError('something wrong in case 1')
        del T[z]
    # case2 指定したzが一つの子を保つ場合
    elif T[z].right is None:
        # 左だけある場合、左の子ノードを親につなぐ
        # 親の左右のどちらにつなぐかはzのつながり方に依存する
        z_is_left = True if T[parent].left == z else False
        child = T[z].left
        if z_is_left:
            T[parent].left = child
        else:
            T[parent].right = child
        T[child].parent = parent
        del T[z]
    elif T[z].left is None:
        # ROOTが片方の部分木しかない場合でROOTを削除しようとするコーナーケースに実は引っかかるはず(実は嘘解法)
        z_is_left = True if T[parent].left == z else False
        child = T[z].right
        if z_is_left:
            T[parent].left = child
        else:
            T[parent].right = child
        T[child].parent = parent
        del T[z]
    # case3 zが2つの子を保つ場合
    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_in_descendants(
            T, T[z].right)  # 指定したノードの子孫の中で一番小さいノードを返す #ここが問題だ node_next_moreがrightと一致するときにparentとかの代入がいろいろおかしくなる
        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:
                # node_next_more==rightとなるような場合
                T[right].parent = None
                T[right].left = left
                ROOT = right
                del T[z]
                return
            else:
                # node_next_moreがもっと下流にある場合
                # zの子と親との接続
                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右子の接続 (node_next_moreの親からみると左に接続される)
                if next_more_right is not None:
                    T[next_more_right].parent = next_more_parent
                ROOT = node_next_more
                del T[z]
                return
        else:  # zが非ROOT
            # zが親からみてどっち側についているか
            z_is_left = True if T[parent].left == z else False
            if node_next_more == right:
                if z_is_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 z_is_left:
                    T[parent].left = node_next_more
                else:
                    T[parent].right = node_next_more
                # next_more -> zの子との接続
                T[node_next_more].left = T[z].left
                T[node_next_more].right = T[z].right
                T[node_next_more].parent = parent
                T[left].parent = node_next_more  # zの左側の接続
                T[right].parent = node_next_more  # zの左側の接続
                # node_next_moreの親 → 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


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


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


    # データの読み込み
N = int(input())
T = {}
for i in range(N):
    tmp = input()
    if tmp.startswith('print'):  # なぜかtmp == 'print'ではerror
        print_result(T)
    elif tmp.startswith('insert'):
        z = int(tmp.split()[1])
        if i == 0:
            ROOT = z
        insert(T, ROOT, z)
    elif tmp.startswith('find'):
        z = int(tmp.split()[1])
        if find(T, ROOT, z) is None:
            print('no')
        else:
            print('yes')
    elif tmp.startswith('delete'):
        z = int(tmp.split()[1])
        delete_node(T, z)

Submission status: Accepted

Solution code:
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write

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 = root #Tの根
    y = None #親を設定
    while x is not None:
        y = x
        if key < x.key:
            x = x.left #左の子へ移動
        else:
            x = x.right  #右の子へ移動

    if y is None: #Tが空の場合
        root = Node(key)
    elif key < y.key:
        y.left = Node(key) #keyをyの左の子にする
    else:
        y.right = Node(key) #keyをyの右の子にする

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 find(key):
#     x = root
#     while x and key != x.key:
#         x = x.left if key < x.key else x.right
#     return x is None

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 # result が None ⇒ false

def inorder(node):
    return   inorder(node.left) + " "+ str(node.key) + inorder(node.right) if node else ''
def preorder(node):
    return   " " + str(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] == 'f':
        if find(int(e[5:])):
            print("no")
        else:
            print("yes")
        # print(['yes','no'][find(int(e[5:]))])

    elif e[0] == 'd':
        delete(int(e[7:]))

    else:
        print(inorder(root))
        print(preorder(root))

Submission status: Accepted

Solution code:
INFTY=2000000000+1

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

root=-1
T=[]
commands=[]
preorderList=[]
inorderList=[]

def readinput():
    global commands

    n=int(input())
    for _ in range(n):
        s=input().split()
        command=s[0]
        if(len(s)>1):
            op=s[1]
        commands.append((command,int(op)))

def insert(op):
    global T
    global root

    #print('[{}]'.format(op))
    zidx=len(T)
    z=Node(op)
    T.append(z)

    yidx=-1
    xidx=root
    while(xidx != -1):
        x=T[xidx]
        yidx=xidx
        if(z.key<x.key):
            xidx=x.left
            #print('left: {} < {}'.format(z.key, x.key))
        else:
            xidx=x.right
            #print('right')
    z.parent=yidx

    if yidx==-1:
        root=zidx
        #print('root changed')
    elif z.key<T[yidx].key:
        T[yidx].left=zidx
    else:
        T[yidx].right=zidx

def bisearch(p,op):
    '''再帰を使わないバージョン
    '''
    global T

    x=p
    while(x != -1 and T[x].key != op):
        if (op < T[x].key):
            x=T[x].left
        else:
            x=T[x].right
    return x


def find(op):
    ans=bisearch(root,op)
    if(ans!=-1):
        print('yes')
    else:
        print('no')

def delete1(target):
    '''子を持たないノードの削除
    '''
    global T

    node=T[target]
    parent=T[node.parent]
    if (T[parent.left].key==node.key):
        parent.left=-1
    else:
        parent.right=-1
    node.parent=-1

def delete2(target):
    '''子を1個持つノードの削除
    '''
    global T

    node=T[target]
    parent=T[node.parent]
    if(node.left!=-1):
        childIdx=node.left
        node.left=-1
    else:
        childIdx=node.right
        node.right=-1
    if(T[parent.left].key==node.key):
        parent.left=childIdx
    else:
        parent.right=childIdx
    T[childIdx].parent=node.parent
    node.parent=-1

def delete3(target):
    '''子を2子持つノード
    '''
    global T
    global inorderList

    #print('[delete3]:{}'.format(T[target].key))
    node=T[target]
    inorderList=[]
    getInorderList(node.right) # ; printInorderList()
    nextIdx=inorderList[0]
    node.key=T[nextIdx].key
    nextType=getType(nextIdx)
    if(nextType==1):
        delete1(nextIdx)
    else:
        delete2(nextIdx)


def getType(target):
    global T

    node=T[target]
    if(node.left==-1 and node.right==-1):
        return 1
    elif(node.left==-1 or node.right==-1):
        return 2
    else:
        return 3

def delete(op):
    target=bisearch(root,op)
    type=getType(target)
    if(type==1):
        delete1(target)
    elif(type==2):
        delete2(target)
    else:
        delete3(target)
    
def getPreorderList(id):
    global preorderList

    preorderList.append(id)
    node=T[id]
    if(node.left!=-1):
        getPreorderList(node.left)
    if(node.right!=-1):
        getPreorderList(node.right)

def getInorderList(id):
    global inorderList

    node=T[id]
    if(node.left!=-1):
        getInorderList(node.left)
    inorderList.append(id)
    if(node.right!=-1):
        getInorderList(node.right)

def printPreorderList():
    for i in preorderList:
        print(' '+str(T[i].key),end='')
    print('')

def printInorderList():
    for i in inorderList:
        print(' '+str(T[i].key),end='')
    print('')

def printT():
    global inorderList
    global preorderList

    inorderList=[]
    preorderList=[]
    
    getInorderList(root)
    printInorderList()
    getPreorderList(root)
    printPreorderList()
    #for node in T:
    #    print(node.key, node.parent, node.left, node.right)    

def main():
    global commands

    for command,op in commands:
        if(command=='insert'):
            insert(op)
        elif(command=='find'):
            find(op)
        elif(command=='delete'):
            delete(op)
        elif(command=='print'):
            printT()

if __name__=='__main__':
    readinput()
    main()

Submission status: Accepted

Solution code:

import sys
sys.setrecursionlimit(10 ** 7)
read = sys.stdin.buffer.read
inp = sys.stdin.buffer.readline
def inpS(): return inp().rstrip().decode()
readlines = sys.stdin.buffer.readlines
MOD = 10 ** 9 + 7
INF = 1 << 60

# ---------------------------------------------------
# ---------------------------------------------------
# ---------------------------------------------------


def resolve():
    class Node:
        def __init__(self, data):
            self.root = data
            self.left = None
            self.right = None

    class BST:
        def __init__(self):
            self.node = None

        def insert(self, data):
            if self.node is None:
                self.node = Node(data)
            else:
                self._insert(data, self.node)

        def _insert(self, data, cur_node):
            if data < cur_node.root:
                if cur_node.left is None:
                    cur_node.left = Node(data)
                else:
                    self._insert(data, cur_node.left)
            elif data > cur_node.root:
                if cur_node.right is None:
                    cur_node.right = Node(data)
                else:
                    self._insert(data, cur_node.right)
            else:
                print("同じ値があります。")

        def pre_order_print(self):
            if self.node:
                self._pre_order_print(self.node)

        def _pre_order_print(self, cur_node):
            if cur_node:
                print(" ", end="")
                print(cur_node.root, end="")
                self._pre_order_print(cur_node.left)
                self._pre_order_print(cur_node.right)

        def in_order_print(self):
            if self.node:
                self._in_order_print(self.node)

        def _in_order_print(self, cur_node):
            if cur_node:
                self._in_order_print(cur_node.left)
                print(" ", end="")
                print(cur_node.root, end="")
                self._in_order_print(cur_node.right)

        def find_rec(self, data):
            if self.node:
                is_found = self._find(data, self.node)
                if is_found:
                    return True
                return False
            else:
                return None

        def _find(self, data, cur_node):
            if data > cur_node.root and cur_node.right:
                return self._find(data, cur_node.right)
            elif data < cur_node.root and cur_node.left:
                return self._find(data, cur_node.left)
            if data == cur_node.root:
                return True

        # 削除する場合の探索
        def find_min(self, cur_node=None):
            if self.node is None:
                return None
            while cur_node.left:
                cur_node = cur_node.left
            return cur_node

        def delete_node(self, data):
            if self.node is None:
                return False
            else:
                self.node = self._delete_node(data, self.node)

        def _delete_node(self, data, cur_node):
            if cur_node is None:
                return cur_node
            if data < cur_node.root:
                cur_node.left = self._delete_node(data, cur_node.left)
            elif data > cur_node.root:
                cur_node.right = self._delete_node(data, cur_node.right)
            else:
                # 子ノードが一つまたはなしの場合
                if cur_node.left is None:
                    tmp = cur_node.right
                    cur_node = None
                    return tmp
                elif cur_node.right is None:
                    tmp = cur_node.left
                    cur_node.left = None
                    return tmp
                # 子ノードが2つの場合は右側の一番小さい値
                tmp = self.find_min(cur_node.right)
                cur_node.root = tmp.root
                cur_node.right = self._delete_node(tmp.root, cur_node.right)
            return cur_node

            # 探索 ループ版 メソッド

        def find_by_while(self, data):
            if self.node is None:
                return None
            cur_node = self.node
            while cur_node:
                if data == cur_node.root:
                    return True
                if data < cur_node.root:
                    cur_node = cur_node.left
                else:
                    cur_node = cur_node.right
            return False

    N = int(input())
    bst = BST()
    lines = sys.stdin.readlines()
    for line in lines:
        s = line.split()

        if s[0] == "insert":
            x = int(s[1])
            bst.insert(x)
        elif s[0] == "find":
            x = int(s[1])
            if bst.find_rec(x):
                print("yes")
            else:
                print("no")
        elif s[0] == "delete":
            x = int(s[1])
            bst.delete_node(x)
        else:
            # 出力規定： 先頭に1つの空白もいれる
            bst.in_order_print()
            print()
            bst.pre_order_print()
            print()


if __name__ == '__main__':
    resolve()

Submission status: Accepted

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

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

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

def Preorder(target:Node):
    yield target.key
    if target.left != None:
        yield from Preorder(target.left)
    if target.right != None:
        yield from Preorder(target.right)

def Inorder(target:Node):
    if target.left != None:
        yield from Inorder(target.left)
    yield target.key
    if target.right != None:
        yield from Inorder(target.right)

def find(target:Node,findkey:int):
    return node_of_key(target, findkey) != None

def node_of_key(target:Node,findkey:int):
    if target.key == findkey:
        return target
    elif target.key > findkey:
        if target.left:
            return node_of_key(target.left, findkey)
    else:
        if target.right:
            return node_of_key(target.right, findkey)
    return None

def min_value_node_of_tree(root:Node):
    if root.left == None:
        return root
    else:
        return min_value_node_of_tree(root.left)

def delete(target:Node):
    if target.left == None and target.right == None:
        if target.key < target.p.key:
            target.p.left = None
        else:
            target.p.right = None
    elif (target.left == None) ^ (target.right == None):
        child = target.left if target.left else target.right
        child.p = target.p
        if target.key < target.p.key:
            target.p.left = child
        else:
            target.p.right = child
    else:
        next_node = min_value_node_of_tree(target.right)
        target.key = next_node.key
        delete(next_node)

from sys import stdin
tree = Tree()
n = int(input())
lines = stdin.readlines()
for line in lines:
    proc,*key = line.split()
    if proc == "insert":
        tree.insert(Node(int(key[0])))
    elif proc == "find":
        print("yes" if find(tree.root, int(key[0])) else "no")
    elif proc == "delete":
        delete(node_of_key(tree.root, int(key[0])))
    else:
        print(" ",end="")
        print(*Inorder(tree.root))
        print(" ",end="")
        print(*Preorder(tree.root))

Submission status: Accepted

Solution code:
from sys import stdin
N=int(input())
nodes=[None]*N
oya=[None]
class node_tree():
    def __init__(self,node):
        self.node=node
        self.parent=None
        self.left=None
        self.right=None
        self.brother=None
        self.up=None

def ino(u):

    if u.left is not None:
        ino(u.left)
    print("",u.node,end="")
    if u.right is not None:
        ino(u.right)
def pre(u):
    print("",u.node,end="")
    if u.left is not None:
        pre(u.left)
    if u.right is not None:
        pre(u.right)
def search(u,key):
    if u.node <=key.node:
        if u.right is not None:
            u.right.parent=u
            search(u.right,key)
        else:
            u.right=key
            u.right.parent=u
    else:
        if u.left is not None:
            u.left.parent=u
            search(u.left,key)
        else:
            u.left=key
            u.left.parent = u
def find(u,key):
    if u.node==key:
        print("yes",end="")
        return
    if u.node < key:
        if u.right is not None:
            find(u.right, key)
        else:
            print("no",end="")
            return
    else:
        if u.left is not None:
            find(u.left, key)
        else:
            print("no",end="")
            return
def delete_find(u,key):
    if u.node==key:
        return u
    if u.node < key:
        if u.right is not None:
            return delete_find(u.right, key)
    else:
        if u.left is not None:
            return delete_find(u.left, key)
def get(u):#次の次節点を探す
    if u.right is not None:
        return getMini(u.right)
    # y=u.parent
    # while (y is not None and u==y.right):
    #     u=y
    #     y=y.parent
    # return y
def getMini(u):
    while u.left is not None:
        u=u.left
    return u
def delete(z):
    if z.left is None or z.right is None:
        y=z
    else:
        y=get(z)
    if y.left is not None:
        x=y.left
    else:
        x=y.right
    if x is not None:
        x.parent=y.parent
    if y.parent is None:
        oya[0]=x
    elif y==y.parent.left:
        y.parent.left=x
    else:
        y.parent.right=x
    if y!=z:
        z.node=y.node
command_list=[]*N
for i in range(N):
    command_list.append((stdin.readline().strip().split()))
for i,command in enumerate(command_list):
    if len(command)!=1:
        if command[0]=="find":
            find(nodes[0],int(command[1]))
            print()
        elif command[0]=="delete":
            key=int(command[1])
            if oya[0] is None:
                z=delete_find(nodes[0],key)
            else:
                z=delete_find(oya[0],key)
            delete(z)
        else:
            key=int(command[1])
            if i==0:
                nodes[i]=node_tree(key)
            else:
                ins=node_tree(key)
                if oya[0] is None:
                    search(nodes[0],ins)
                    nodes[i]=ins
                else:
                    search(oya[0],ins)
                    nodes[i]=ins
    else:
        if oya[0] is None:
            ino(nodes[0])
            print()
            pre(nodes[0])
            print()
        else:
            ino(oya[0])
            print()
            pre(oya[0])
            print()