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

N = int(input())
trees = [list(input().split()) for i in range(N)]

class BinaryTree:
    def __init__(self,key,p=None,l=None,r=None):
        self.key = key
        self.p = p
        self.l = l
        self.r = r

def Insert(root,z):
    y = None
    x = root
    while x != None:
        y = x
        if z.key < x.key:
            x = x.l
        else:
            x = x.r
    z.p = y

    if y == None:
        root = z
    elif z.key < y.key:
        y.l = z
    else:
        y.r = z
    return root

def preOrder(x):
    if x == None:
        return
    global preList
    preList.append(x.key)
    
    preOrder(x.l)
    preOrder(x.r)

def inOrder(x):
    if x == None:
        return
    inOrder(x.l)

    global inList
    inList.append(x.key)
    
    inOrder(x.r)

def Find(x,z):
    while x != None and z.key != x.key:
        y = x
        if z.key < x.key:
            x = x.l
        else:
            x = x.r
    return x


def Delete(x, z):
    if z.l == None or z.r == None:
        y = z
    else:
        y = getSuccessor(z)

    if y.l != None:
        x = y.l
    else:
        x = y.r

    if x != None:
        x.p = y.p

    if y.p == None:
        pass
    elif y == y.p.l:
        y.p.l = x
    else:
        y.p.r = x
    if y != z:
        z.key = y.key
        
def getSuccessor(x):
    if x.r != None:
        return getMinimum(x.r)
    y = x.p
    while y != None and x == y.r:
        x = y
        y = y.p
    return y

def getMinimum(x):
    while x.l != None:
        x = x.l
    return x

root = None
for data in trees:
    if data[0] == "print":
        inList = []
        preList = []
        inOrder(root)
        a = " " + " ".join([str(num) for num in inList])
        print(a)

        preOrder(root)
        a = " " + " ".join([str(num) for num in preList])
        print(a)

    else:
        z = BinaryTree(int(data[1]))
        if data[0] == "insert":
            root = Insert(root,z)
        elif data[0] == "find":
            a = Find(root, z)
            if a == None:
                print("no")
            else:
                print("yes")
        elif data[0] == "delete":
            Delete(root, Find(root,z))

Solution (Python):
import sys

tree={}
np = -1

home=0
tree[home]=[None, None, None]

def search(p, x):
    node_pos=[None,None]
    while p != None:
        tmp = tree[p]
        if tmp[0] == x:
            node_pos[0] = p
            return node_pos
        node_pos[1] = p
        if x < tmp[0]:
            p = tmp[1]
        else:
            p = tmp[2]
    return node_pos

def node(x):
    global np
    np += 1
    tree[np] = [x, None, None]
    return np

def insert(p, x):
    if p == None or np == -1: return node(x)
    tmp = tree[p]
    if x== tmp[0]: return p
    elif x<tmp[0]:
        tree[p][1]=insert(tmp[1],x)
    else:
        tree[p][2]=insert(tmp[2],x)
    return p

def deletenode(p, parent, child=None):
        if tree[parent][1]==p:
            tree[parent][1] = child
        elif tree[parent][2]==p:
            tree[parent][2] = child
        del tree[p]

def searchmin(p):
    while tree[p][1]!=None:
        p = tree[p][1]
    return p

def delete(x):
    p, parent = search(0,x)
    if tree[p][1:3]==[None,None]:
        deletenode(p,parent)
    elif tree[p][1]==None:
        deletenode(p, parent, tree[p][2])
    elif tree[p][2]==None:
        deletenode(p, parent, tree[p][1])
    else:
        p1=searchmin(tree[p][2])
        p1, parent1 = search(0,tree[p1][0])

        if tree[parent1][1]==p1:
            tree[parent1][1] = None
        elif tree[parent1][2]==p1:
            tree[parent1][2] = None

        if tree[parent][1]==p:
            tree[parent][1] = p1
        elif tree[parent][2]==p:
            tree[parent][2] = p1
        tree[p1][1]=tree[p][1]
        tree[p1][2]=tree[p][2]
        del tree[p]
    return

def preorder(p):
    if p == None: return []
    p1, p2 = tree[p][1:3]
    return [tree[p][0]] + preorder(p1) + preorder(p2)

def inorder(p):
    if p == None: return []
    p1, p2 = tree[p][1:3]
    return inorder(p1) + [tree[p][0]] +inorder(p2)

n = int(input())
i = 0
while i<n:
    s = raw_input()
    if s[0]=='i':
        p = insert(0,int(s[7:]))
    elif s[0]=='f':
        if search(0,int(s[5:]))[0]!=None: print 'yes'
        else: print 'no'
    elif s[0]=='d':
        delete(int(s[7:]))
    elif s[0]=='p':
        print ' ' + ' '.join(map(str, inorder(home)))
        print ' ' + ' '.join(map(str, preorder(home)))
    i += 1

Solution (Python):

from __future__ import division, print_function
from sys import stdin


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


def tree_insert(top, z):
    y = None
    x = top
    while isinstance(x, Node):
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right
    z.parent = y
    if y is None:
        top = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z
    return top


def tree_find(node, key):
    if not node:
        return None
    if node.key == key:
        return node
    if key < node.key:
        return tree_find(node.left, key)
    return tree_find(node.right, key)


def tree_delete(top, z):
    if z.left is None or z.right is None:
        y = z
    else:
        y = tree_successor(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:
        top = x
    elif y == y.parent.left:
        y.parent.left = x
    else:
        y.parent.right = x

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


def tree_successor(x):
    if x.right is not None:
        return tree_minimum(x.right)
    y = x.parent
    while y is not None and x == y.right:
        x = y
        y = y.parent
    return y


def tree_minimum(x):
    while x.left is not None:
        x = x.left
    return x


def inorder_walk(node):
    if node.left:
        inorder_walk(node.left)
    print('', node.key, end='')
    if node.right:
        inorder_walk(node.right)


def preorder_walk(node):
    print('', node.key, end='')
    if node.left:
        preorder_walk(node.left)
    if node.right:
        preorder_walk(node.right)


n = int(stdin.readline())


top = None
for _ in range(n):
    cmd = stdin.readline()
    if cmd.startswith('i'):
        key = int(cmd[7:])
        
        top = tree_insert(top, Node(key))
    elif cmd.startswith('f'):
        key = int(cmd[5:])
        r = tree_find(top, key)
        print('yes' if r else 'no')
    elif cmd.startswith('d'):
        key = int(cmd[7:])
        node = tree_find(top, key)
        if node:
            top = tree_delete(top, node)
    else:
        inorder_walk(top)
        print()
        preorder_walk(top)
        print()

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

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

def pre_parse(T: dict, u: int, pre_ls: list):
    if u is 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: dict, u: int, in_ls: list):
    if u is 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: dict, ROOT: int , z: int):
    if ROOT == z:
        T[z] = Node()
    else:
        T[z] = Node()
        x = ROOT
        while x is not None: 
            next_parent = x
            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: dict, ROOT: int, k: int):
    """
    Tからkを見つけ出す。見つからなかったらNoneを返す
    """
    x = ROOT
    while x is not None and x != k:
        if k < x:
            x = T[x].left
        else:
            x = T[x].right
    return x

def delete_node(T: dict, z: int):
    
    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
        del T[z]
    
    
    elif T[z].right is None:
        
        is_z_left = True if T[parent].left == z else False
        child = T[z].left
        if is_z_left: 
            T[parent].left = child
        else: 
            T[parent].right = child
        T[child].parent = parent
        del T[z]
    
    elif T[z].left is None:
        
        is_z_left = True if T[parent].left == z else False
        child = T[z].right
        if is_z_left: 
            T[parent].left = child
        else: 
            T[parent].right = child
        T[child].parent = parent
        del T[z]
    
    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_descendants(T, T[z].right)
        next_more_right = T[node_next_more].right
        next_more_parent = T[node_next_more].parent
        
        if parent is None:
            if node_next_more == right:
                T[right].parent = None
                T[right].left = left
                ROOT = right
                del T[z]
                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 
                
                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
        
        else: 
            is_z_left = True if T[parent].left == z else False
            if node_next_more == right:
                
                if is_z_left:
                    T[parent].left = right
                else:
                    T[parent].right = right
                T[right].parent = parent
                T[right].left = left
                del T[z]
                return
            else:
                
                if is_z_left:
                    T[parent].left = node_next_more
                else:
                    T[parent].right = node_next_more
                
                T[node_next_more].left = left
                T[node_next_more].right = 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[z]
                return

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

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

def main():
    N = int(input())
    T = {}
    ROOT = 0
    for i in range(N):
        tmp = input().split()
        if tmp[0] == "insert":
            value = int(tmp[1])
            if i==0:
                ROOT = value
            insert(T, ROOT, value)
        elif tmp[0] == "find":
            value = int(tmp[1])
            if find(T, ROOT, value):
                print("yes")
            else:
                print("no")
        elif tmp[0] == "delete":
            value = int(tmp[1])
            delete_node(T, value)
        else:
            print_result(T, ROOT)

main()

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

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_lis: list):
    if u == None:
        return
    pre_lis.append(u)
    pre_parse(T, T[u].left, pre_lis)
    pre_parse(T, T[u].right, pre_lis)

def in_parse(T,u,in_lis):
    if u == None:
        return
    in_parse(T, T[u].left, in_lis)
    in_lis.append(u)
    in_parse(T, T[u].right, in_lis)

def insert(T, Root, z):
    
    
    
    if Root == z:
        T[z] = Node()
    
    else:
        T[z] = Node()
        x = Root
        while x is not None:
            
            next_parent = x
            if x > z:
                x = T[x].left
                temp = 1
            else:
                x = T[x].right
                temp = 2

        T[z].parent = next_parent
        if temp == 1:
            T[next_parent].left = z
        else:
            T[next_parent].right = z

def find(T,Root,k):
    
    x = Root
    while x != None and x != k:
        if k < x:
            x = T[x].left
        else:
            x = T[x].right
    return x

def delete_node(T,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]

    
    elif T[z].right is None:
        
        
        z_is_left = True if T[parent].left == z else False
        child = T[z].left
        if z_is_left:
            T[parent].left = child
            T[child].parent = parent
            del T[z]
        else:
            T[parent].right = child
            T[child].parent = parent
            del T[z]

    elif T[z].left is None:
        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]

    
    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)
        next_more_right = T[node_next_more].right
        next_more_parent = T[node_next_more].parent
        
        if parent is None:
            if node_next_more == right:
                
                T[right].parent = None
                T[right].left = left
                Root = right
                del T[z]
                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 is not None:
                    T[next_more_right].parent = next_more_parent
                    T[next_more_parent].left = next_more_right
                Root = node_next_more
                del T[z]
                return

        else:
            
            
            z_is_left = True if T[parent].left == z else False
            if node_next_more == right:
                if z_is_left:
                    T[parent].left = node_next_more
                else:
                    T[parent].right = node_next_more

                T[node_next_more].parent = parent
                T[node_next_more].left = left
                del T[z]
                return
            else:
                
                if z_is_left:
                    T[parent].left = node_next_more
                else:
                    T[parent].right = node_next_more

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

Solution (Python):
NIL = -1

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

def getAncestor(t, n):
    for i in range(n):
        if t[i].parent == -1:
            return i

def preOrderWolk(t, u, load=[]):
    load.append(u.key)
    if u.left != -1:
        load = preOrderWolk(t, u.left, load)
    if u.right != -1:
        load = preOrderWolk(t, u.right, load)
    return load

def preorder(u):
    if u == NIL:
        return
    print(' ' + str(u['key']), end='')
    preorder(u['left'])
    preorder(u['right'])

def inorder(u):
    if u == NIL:
        return
    inorder(u['left'])
    print(' ' + str(u['key']), end='')
    inorder(u['right'])

def inOrderTreeWalk(t, u, load=[]):
    if u.left != -1:
        load = inOrderTreeWalk(t, u.left, load)
    load.append(u.key)
    if u.right != -1:
        load = inOrderTreeWalk(t, u.right, load)
    return load

def find(x, k):
    """[finding Node which has key k]

    Args:
        x ([root Node]): [description]
        k ([int]): [description]
    """    
    while x != -1 and k != x.key:
        if k < x.key:
            x = x.left
        else:
            x = x.right
    return x


def insert(T, z):
    """[insert z to tree T]

    Args:
        T ([list]): [description]
        z ([Node class]): [Node ]
        r ([int]): [root intger]
    """
    y = NIL 
    x = T[0]
    while x != NIL and x.key != None:
        y = x
        if z.key < x.key:
            x = x.left
        elif z.key > x.key:
            x = x.right
    z.parent = y

    if y == NIL: 
        T[0] = z
    elif z.key < y.key:
        T.append(z)
        y.left = z
    else:
        T.append(z)
        y.right = z

def getSuccessor(x):
    """[finding node that succes the Node]

    Args:
        x ([node]): [description]
    """
    if x.right != -1:
        return getMinimum(x.right)
    
    print('arienai')
    y = x.parent
    while y != -1 and x == y.right:
        x = y
        y = y.parent
    return y

def getMinimum(x):
    while x.left != -1:
        x = x.left
    return x

def delete(T, z):
    """[delete Node z]

    Args:
        T ([list]): [description]
        z ([node]): [node with key]
    """    
    
    if z.left == -1 or z.right == -1:
        y = z
    else:
        y = getSuccessor(z)

    
    if y.left != -1:
        x = y.left
    else:
        x = y.right

    if x != -1:
        x.parent = y.parent
    if y.parent == -1:
        T[0] = x
    elif y == y.parent.left:
        y.parent.left = x
    else:
        y.parent.right = x

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

import sys
T = [Node(None)]
n = int(input())
r = 0
for _ in range(n):
    in_ = sys.stdin.readline().split()
    if in_[0][0] == 'i':
        z = Node(int(in_[1]))
        insert(T, z)
    elif in_[0][0] == 'd':
        key = int(in_[1])
        x = find(T[0], key)
        delete(T, x)

    elif in_[0][0] == 'f':
        key = int(in_[1])
        x = find(T[0], key)
        if x !=  -1:
            print('yes')
        else:
            print('no')
    else:
        pre = preOrderWolk(T, T[0], [])
        in_ = inOrderTreeWalk(T, T[0], [])
        print('',*in_) 
        print('',*pre)

Solution (Python):
class BinarySearchTree:
    def __init__(self):
        self.root = None
    def show_keys(self):
        in_order_from(self.root)
        print('')
        pre_order_from(self.root)
        print('')
    def insert(self, key):
        node = Node(key)
        insert(self, node)
    def find(self, key):
        if find_from(self.root, key):
            print('yes')
        else:
            print('no')
    def delete_key(self, key):
        node = find_from(self.root, key)
        delete_node(self, node)

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

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

def delete_node(T, node):
    if node.left and node.right:
        x = node.right
        while x.left:
            x = x.left
        node.key = x.key
        delete_node(T, x)
    elif node.left or node.right:
        child = node.left or node.right
        if node is T.root:
            T.root = child
            child.parent = None
        else:
            if node.parent.left is node:
                node.parent.left = child
                child.parent = node.parent
            else:
                node.parent.right = child
                child.parent = node.parent
    else:
        if node.parent.left is node:
            node.parent.left = None
        else:
            node.parent.right = None

def in_order_from(node):
    if node:
        in_order_from(node.left)
        print(' {0}'.format(node.key), end = '')
        in_order_from(node.right)

def pre_order_from(node):
    if node:
        print(' {0}'.format(node.key), end = '')
        pre_order_from(node.left)
        pre_order_from(node.right)

def find_from(node, k):
    while node:
        if node.key == k:
            return node
        if k < node.key:
            node = node.left
        else:
            node = node.right


import sys

t = BinarySearchTree()

m = sys.stdin.readline()

for i in sys.stdin.readlines():
    if i[0] == 'i':
        t.insert(int(i[7:]))
    elif i[0] == 'f':
        t.find(int(i[5:]))
    elif i[0] == 'd':
        t.delete_key(int(i[7:]))
    else:
        t.show_keys()

Solution (Python):
import sys, os, math, bisect, itertools, collections, heapq, queue, copy, array





sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


class BinaryNode:
    def __init__(self, key, left=None, right=None):
        self.val = key
        self.left = left
        self.right = right


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


def preorder(root):
    ret = []
    if root is None: return ret
    ret.append(root.val)
    ret.extend(preorder(root.left))
    ret.extend(preorder(root.right))
    return ret


def inorder(root):
    ret = []
    if root is None: return ret
    ret.extend(inorder(root.left))
    ret.append(root.val)
    ret.extend(inorder(root.right))
    return ret


def find(node, key):
    while node is not None and key != node.val:
        if key < node.val:
            node = node.left
        else:
            node = node.right
    return node


def get_min_node(node):
    current = node
    while current.left is not None:
        current = current.left
    return current


def get_min_node(node):
    current = node
    while current.left is not None:
        current = current.left
    return current


def delete(root, key):
    if root is None:
        return root

    if key < root.val:
        root.left = delete(root.left, key)
    elif key > root.val:
        root.right = delete(root.right, key)
    else:
        if root.left is None:
            temp = root.right
            root = None
            return temp
        elif root.right is None:
            temp = root.left
            root = None
            return temp

        temp = get_min_node(root.right)
        root.val = temp.val
        root.right = delete(root.right, temp.val)
    return root


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N = ii()
    s, key = sl()
    root = BinaryNode(int(key))

    for n in range(N - 1):
        input = sl()
        if input[0] == 'print':
            print("", *inorder(root))
            print("", *preorder(root))
        elif input[0] == 'find':
            node = find(root, int(input[1]))
            print('yes' if node is not None else 'no')
        elif input[0] == 'delete':
            root = delete(root, int(input[1]))
        else:
            insert(root, BinaryNode(int(input[1])))


if __name__ == '__main__':
    main()

Solution (Python):
class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None
        self.parent = None
    
    def delete_connect(self, parent, child):
        if parent:
            if parent.val > self.val:
                parent.left = child
            else:
                parent.right = child
        if child:
            child.parent = parent
    
    def delete(self):
        left, right = self.left, self.right
        if not left and not right:
            self.delete_connect(self.parent, None)
        elif not left and right:
            self.delete_connect(self.parent, right)
        elif left and not right:
            self.delete_connect(self.parent, left)
        else:
            next_node = right.get_leftmost()
            self.val = next_node.val
            next_node.delete()
    
    def get_leftmost(self):
        if self.left:
            return self.left.get_leftmost()
        return self


class BinarySearchTree:
    def __init__(self):
        self.root = None
    
    def insert(self, node: Node):
        if not self.root:
            self.root = node
            return

        cur = self.root
        while cur:
            if node.val > cur.val:
                if cur.right:
                    cur = cur.right
                    continue
                else:
                    cur.right,node.parent = node,cur
                    return
            else:
                if cur.left:
                    cur = cur.left
                    continue
                else:
                    cur.left,node.parent = node,cur
                    return

    def find(self, val):
        cur = self.root
        while cur:
            if cur.val == val:
                return "yes"
            elif cur.val > val:
                cur = cur.left
            else:
                cur = cur.right
        return "no"
    
    def find_node(self, val):
        cur = self.root
        while cur:
            if cur.val == val:
                return cur
            elif cur.val > val:
                cur = cur.left
            else:
                cur = cur.right
        return None

    def delete(self, val):
        node = self.find_node(val)
        if node:
            node.delete()

def main():

    
    preorder = []

    def preorder_walk(node):
        preorder.append(str(node.val))
        if node.left:
            preorder_walk(node.left)
        if node.right:
            preorder_walk(node.right)

    

    inorder = []

    def inorder_walk(node):
        if node.left:
            inorder_walk(node.left)
        inorder.append(str(node.val))
        if node.right:
            inorder_walk(node.right)


    n = int(input())
    
    bst = BinarySearchTree()
    
    for _ in range(n):
        op = input().strip().split()
        if op[0] == "insert":
            bst.insert(Node(int(op[1])))
        elif op[0] == "print":
            preorder,inorder = [],[]
            preorder_walk(bst.root)
            inorder_walk(bst.root)
            print(""," ".join(inorder))
            print("", " ".join(preorder))
        elif op[0] == "find":
            print(bst.find(int(op[1])))
        elif op[0] == "delete":
            bst.delete(int(op[1]))

if __name__ == "__main__":
    main()