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:
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 no parent
    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 が空の場合
        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]
    """    
    # 削除する対象の節点をyとする
    if z.left == -1 or z.right == -1:
        y = z
    else:
        y = getSuccessor(z)

    # yの子xを決める
    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_) #inOrder
        print('',*pre) #preOrder

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys, os, math, bisect, itertools, collections, heapq, queue, copy, array

# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
# from decimal import Decimal
# from collections import defaultdict, deque

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

Submission status: Accepted

Solution code:
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 tree walk
    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 tree walk

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

Submission status: Accepted

Solution code:
class BinaryTree:
    def __init__(self, left, right, parent):
        self.left = left
        self.right = right
        self.parent = parent
        self.key = None
        self.root = False
        

def insert(T, z):
    global root
    
    y = -1
    try:
        x = root
    except:
        x = -1
        root = z
        T[z].root = True
    
    while x != -1:
        y = x
        if T[z].key < T[x].key:
            x = T[x].left
        else:
            x = T[x].right
    T[z].parent = y
    
    if y == -1:
        pass
    
    elif T[z].key < T[y].key:
        T[y].left = z
        
    else:
        T[y].right = z

def find(T, z, s):
    if s == -1:
        return [False, None]
        
    elif T[s].key == z:
        return [True, s]
        
    elif T[s].key < z:
        return find(T, z, T[s].right)
        
    else:
        return find(T, z, T[s].left)

def delete(T, z):
    global root
    z_has_left = T[z].left != -1
    z_has_right = T[z].right != -1
    
    
    if (not z_has_left) or (not z_has_right):
        y = z
    else:
        y = getsucsessor(T, z)


    if T[y].left != -1:
        x = T[y].left
    else:
        x = T[y].right
    
    if x != -1:
        T[x].parent = T[y].parent
    
    if T[y].root:
        T[x].root = True
        T[y].root = False
        root = x
    
    elif T[T[y].parent].left == y:
        T[T[y].parent].left = x
    else:
        T[T[y].parent].right = x
    
    T[z].key = T[y].key
    T[y] = BinaryTree(-1, -1, -1)

def getsucsessor(T, x):
    if T[x].right != -1:
        
        return getMinimum(T, T[x].right)
        
    else:
        y = T[x].parent
        while (y != -1) and (T[y].right == x):
            x = y
            y = T[y].parent
        return y

def getMinimum(T, x):
    while T[x].left != -1:
        x = T[x].left
    return x
        
    
def preParse(u):
    if u == -1:
        return 0
    print(" " + str(T[u].key), end="")
    preParse(T[u].left)
    preParse(T[u].right)

def inParse(u):
    if u == -1:
        return 0
    inParse(T[u].left)
    print(" " + str(T[u].key), end="")
    inParse(T[u].right)

m = int(input().rstrip())

z = 0
T = []
for _ in range(m):
    T.append(BinaryTree(-1, -1, -1))

for _ in range(m):
    command = input().rstrip()
    if command =="print":
        inParse(root)
        print()
        preParse(root)
        print()
    else:
        command, key = command.split(" ")
        key = int(key)
    
    
    if command == "insert":
        T[z].key = key
        insert(T, z)
        z += 1
        
    elif command == "find":
        if find(T, key, root)[0]:
            print("yes")
        else:
            print("no")
    
    elif command == "delete":
        x = find(T, key, root)[1]
        
        delete(T, x)

Submission status: Accepted

Solution code:
n=int(input())
tree={}
root=None

def insert(tree,number):
    parent=None
    children=root
    while children!=None:
        parent=children
        if number>children:
            children=tree[parent][1]
        else:
            children=tree[parent][0]
    tree[number][2]=parent
    if number>parent:
        tree[parent][1]=number
    else:
        tree[parent][0]=number

def preorder(tree,i):
    if i==None:
        return
    print(" {}".format(i),end="")
    preorder(tree,tree[i][0])
    preorder(tree,tree[i][1])

def inorder(tree,i):
    if i==None:
        return
    inorder(tree,tree[i][0])
    print(" {}".format(i),end="")
    inorder(tree,tree[i][1])

def find(x,number):
    while x!=None and number!=x:
        if x>number:
            x=tree[x][0]
        else:
            x=tree[x][1]
    return x

def find_parent(x,number):
    y=0
    t=-1
    while x!=None and number!=x:
        y=x
        if x>number:
            x=tree[x][0]
            t=0
        else:
            x=tree[x][1]
            t=1
    return y,t

def get_minimum(tree,number):
    while tree[number][0]!=None:
        number=tree[number][0]
    return number    

def delete(tree,number):
    if tree[number][0]==None and tree[number][1]==None:
        y,t=find_parent(root,number)
        tree[y][t]=None
    elif tree[number][0]==None or tree[number][1]==None:
        if tree[number][0]==None:
            next_number=tree[number][1]
        else:
            next_number=tree[number][0]
        y,t=find_parent(root,number)
        tree[y][t]=next_number
    elif tree[number][0]!=None and tree[number][1]!=None:
        next_number=get_minimum(tree,tree[number][1])
        y,t=find_parent(root,number)
        next_y,next_t=find_parent(root,next_number)
        left,right=tree[number][0],tree[number][1]
        if tree[number][1]==next_number:
            right=None
        tree[y][t]=next_number
        tree[next_y][next_t]=None
        tree[next_number]=[left,right]


for i in range(n):
    tmp=list(input().split())
    if tmp[0]=="print":
        inorder(tree,root)
        print()
        preorder(tree,root)
        print()
    else:
        number=int(tmp[1])
        if tmp[0]=="insert":
            if root==None:
                root=number
                tree[number]=[None,None,None]
            else:
                tree[number]=[None,None,None]
                insert(tree,number)
            
        elif tmp[0]=="find":
            if find(root,number) is not None:
                print("yes")
            else:
                print("no")
        
        else:
            delete(tree,number)

Submission status: Accepted

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

class Tree:
    root = None
    preorder_list = []
    inorder_list = []
    def __init__(self):
        pass
    def insert(self, node):
        y = None
        x = self.root

        while x is not None:
            y = x
            if node.key < x.key:
                x = x.left
            else:
                x = x.right
        node.parent = y

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

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

    def delete(self, node):
        y = None
        x = self.root

        while x is not None:
            y = x
            if node.key < x.key:
                x = x.left
            elif node.key > x.key:
                x = x.right
            else:
                break
        if y.left is None and y.right is None:
            if y.parent.left == y:
                y.parent.left = None
            if y.parent.right == y:
                y.parent.right = None
        elif y.left is None or y.right is None:
            tmp = y.left or y.right
            tmp.parent = y.parent
            if tmp.parent.left == y:
                tmp.parent.left = tmp
            if tmp.parent.right == y:
                tmp.parent.right = tmp
        else:
            tmp = self.successor(y)
            y.key = tmp.key
            if tmp.parent.left == tmp:
                tmp.parent.left = None
            if tmp.parent.right == tmp:
                tmp.parent.right = None

            pass

    def successor(self, node):
        node = node.right
        while node.left:
            node = node.left
        return node

    def display(self):
        #print(self.root, self.root.key, self.root.parent, self.root.left, self.root.right)
        self.inorder(self.root)
        self.preorder(self.root)
        print(' '+' '.join(map(str, self.inorder_list)))
        print(' '+' '.join(map(str, self.preorder_list)))
        pass

    def preorder(self, node):
        if node == None:
            return
        self.preorder_list.append(node.key)
        if node.left is not None:
            self.preorder(node.left)
        if node.right is not None:
            self.preorder(node.right)

    def inorder(self, node, depth=0):
        if node == None:
            return
        if node.left is not None:
            self.inorder(node.left)
        self.inorder_list.append(node.key)
        if node.right is not None:
            self.inorder(node.right)

n = int(input())
command_list = [list(input().split()) for _ in range(n)]

tree = Tree()
for command in command_list:
    if command[0] == 'insert':
        node = Node(int(command[1]))
        tree.insert(node)
        #print(node, node.key, node.parent, node.left, node.right)
    if command[0] == 'print':
        tree.display()
        tree.preorder_list = []
        tree.inorder_list = []
    if command[0] == 'find':
        if tree.find(Node(int(command[1]))) is None:
            print('no')
        else:
            print('yes')
    if command[0] == 'delete':
        result = tree.delete(Node(int(command[1])))

Submission status: Accepted

Solution code:
class Node:
    def __init__(self, key):
        self.key = key
        self.parent = None
        self.left = self.right = None
    def nextNode(self):
        if not self.right:
            return None
        x = self.right
        while x.left:
            x = x.left
        return x
    def preorder(self):
        L = [self.key]
        if self.left: L += self.left.preorder()
        if self.right: L += self.right.preorder()
        return L
    def inorder(self):
        L = []
        if self.left: L += self.left.inorder()
        L.append(self.key)
        if self.right: L += self.right.inorder()
        return L

def insert(t, z):
    y = None
    x = t
    while x:
        y = x # 親を設定
        x = x.left if z.key < x.key else x.right
    z.parent = y
    if not y: # t が空の場合
        return z
    if z.key < y.key:
        y.left = z # z を y の左の子にする
    else:
        y.right = z # z を y の右の子にする
    return t

def find(t, k):
    x = t
    while x:
        if x.key == k:
            return x
        x = x.left if k < x.key else x.right
    return None

def delete(t, k):
    node = find(t, k)
    delNode(node)

def delNode(node):
    if not node: return
    if not node.left and not node.right: # 子がないとき
        if node == node.parent.left:
            node.parent.left = None
        if node == node.parent.right:
            node.parent.right = None
    elif not node.right: # 左の子だけのとき
        if node == node.parent.left:
            node.parent.left = node.left
        if node == node.parent.right:
            node.parent.right = node.left
        node.left.parent = node.parent
    elif not node.left: # 右の子だけのとき
        if node == node.parent.left:
            node.parent.left = node.right
        if node == node.parent.right:
            node.parent.right = node.right
        node.right.parent = node.parent
    else: # 子が２つのとき
        next = node.nextNode()
        node.key = next.key
        delNode(next)

t = None
m = int(input())
for _ in range(m):
    cmd = list(input().split())
    if cmd[0] == 'insert':
        t = insert(t, Node(int(cmd[1])))
    if cmd[0] == 'find':
        print('yes' if find(t, int(cmd[1])) else 'no')
    if cmd[0] == 'delete':
        delete(t, int(cmd[1]))
    if cmd[0] == 'print':
        print('', *t.inorder())
        print('', *t.preorder())

Submission status: Accepted

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


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

ROOT = None

def pre_parse(u, pre_ls):
    if u == None:
        return
    pre_ls.append(u.key)
    pre_parse(u.left, pre_ls) 
    pre_parse(u.right, pre_ls)


def in_parse(u, in_ls):
    if u == None:
        return
    in_parse(u.left, in_ls)
    in_ls.append(u.key)
    in_parse(u.right, in_ls)


def insert(value):
    global ROOT
    y = None
    x = ROOT
    z = Node(value)  
    while x != None:
        y = x  
        if z.key < x.key:
            x = x.left
        else:
            x = x.right
            
    z.parent = y

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


def find(u, value):
    while u != None and u.key != value:
        if value < u.key:
            u = u.left
        else:
            u = u.right
    return u


def deleteNode(z):
    
    if (z.left == None or z.right == None):
        y = z
    else:
        y = getSucessor(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:
        ROOT = x
    elif y == y.parent.left:
        y.parent.left = x
    else:
        y.parent.right = x

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

def getSucessor(x):
    if x.right is not None:
        return getMinimum(x.right)

    y = x.parent
    
    while y and x == y.right:
        x = y
        y = y.parent
    return y


def getMinimum(x):
    while x.left != None:
        x = x.left
    return x
    
    
def print_result():
    pre_ls, in_ls = [], []
    in_parse(ROOT, in_ls)
    pre_parse(ROOT, pre_ls)
    print('', *in_ls)
    print('', *pre_ls)

n = int(input())

for i in range(n):
    tmp = input()
    if tmp[0] == "p":
        print_result()
    elif tmp[0] == "f":
        if find(ROOT, int(tmp[5:])):
            print("yes")
        else:
            print("no")
    elif tmp[0] == "i":
        insert(int(tmp[7:]))
    else:
        deleteNode(find(ROOT, int(tmp[7:])))

Submission status: Accepted

Solution code:
import sys
# def input():
#     return sys.stdin.readline()[:-1]

# n = int(input())
# A = [input() for i in range(n)]

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


def insert(key):
    global root
    x = root # x is current node
    y = None  #  parent of x 
    while x:
        y = x # set parent
        if key < x.key:
            x = x.left # move to left child
        else:
            x = x.right #move to right child
    
    if root is None:
        root = Node(key)
    elif key < y.key: # set z as left child of y
        y.left = Node(key)
        y.left.parent = y
    else: 
        y.right = Node(key) # set z as right child of y
        y.right.parent = y
        
def find(key):
    global root
    x = root
    while x:
        if key==x.key:
            print('yes')
            return
        elif key < x.key:
            x = x.left
        else:
            x = x.right
    print('no')
    
    
def minimum(x):
    while x.left:
        x = x.left
    return x
    
    
def successor(x):
    if x.right:
        return minimum(x.right)
    y = x.parent
    while (y) and (x==y.right):
        x = y
        y = y.parent
    return y
    
    
    
def delete(key):
    global root
    
    # find z
    z = None
    x = root
    while x:
        if key==x.key:
            z = x
            break
        elif key < x.key:
            x = x.left
        else:
            x = x.right
    if z is None:
        return
    
    # determin y
    if (z.left==None) or (z.right==None):
        y = z
    else:
        y = successor(z)
        
    if y.left:
        x = y.left
    else:
        x = y.right
        
    if x:
        x.parent = y.parent
    
    if y.parent is None:
        root = x
    elif y==y.parent.left:
        y.parent.left = x
    else:
        y.parent.right = x
        
    if y!=z:
        z.key = y.key
    

def inorder(inorder_list, node):
    if node.left is not None:
        inorder(inorder_list, node.left)
    inorder_list.append(str(node.key))
    if node.right is not None:
        inorder(inorder_list, node.right)
    return inorder_list
        
def preorder(preorder_list, node):
    preorder_list.append(str(node.key))
    if node.left is not None:
        preorder(preorder_list, node.left)
    if node.right is not None:
        preorder(preorder_list, node.right)
    return preorder_list
        
root = None

input()
for o in sys.stdin:
    if o[0]=='i':
        insert(int(o[7:]))
    elif o[0]=='f':
        find(int(o[5:]))
    elif o[0]=='d':
        delete(int(o[7:]))
    else:
        x = root
        inorder_list = inorder([], x)
        print(' '+' '.join(inorder_list))
        preorder_list = preorder([], x)
        print(' '+' '.join(preorder_list))