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

    
    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
            
        else:
            xidx=x.right
            
    z.parent=yidx

    if yidx==-1:
        root=zidx
        
    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

    
    node=T[target]
    inorderList=[]
    getInorderList(node.right) 
    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()
    
    

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()

Solution (Python):

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
                
                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:
            
            bst.in_order_print()
            print()
            bst.pre_order_print()
            print()


if __name__ == '__main__':
    resolve()

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

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

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

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

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

Solution (Python):
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("")

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