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: Time Limit Exceeded

Solution code:
#http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_8_A
#???????????? 15??? 8A????????????

def insert(root, insert_node):
    focus_node = root
    parent = None
    while not focus_node == None:
        parent = focus_node
        if focus_node["data"]  > insert_node["data"]:
            focus_node = focus_node["left"]
        else:
            focus_node = focus_node["right"]

    if parent["data"] > insert_node["data"]:
        parent["left"] = insert_node
        insert_node["parent"] = parent
    else:
        parent["right"] = insert_node
        insert_node["parent"] = parent

def get_preorder(node):
    if node == None:
        return []
    r = []
    r.append(str(node["data"]))
    r.extend(get_preorder(node["left"]))
    r.extend(get_preorder(node["right"]))

    return r
    
def get_inorder(node):
    if node == None:
        return []
    r = []
    r.extend(get_inorder(node["left"]))
    r.append(str(node["data"]))
    r.extend(get_inorder(node["right"]))

    return r

def delete_tree(root, target):
    delete_node = None
    focus_node = root
    parent = None
    node_direction = ""
    while focus_node:
        if target == focus_node["data"]:
            delete_node = focus_node
            break
        elif focus_node["data"] < target:
            parent = focus_node
            node_direction = "right"
            focus_node = focus_node["right"]
        else:
            parent = focus_node
            node_direction = "left"
            focus_node = focus_node["left"]

    if delete_node == None:
        return

    while True:
        if delete_node["left"] == None and delete_node["right"] == None:
            parent[node_direction] = None
            break
        elif delete_node["left"] and delete_node["right"]:
            p = get_inorder(root)
            next_num = int(p[p.index(str(delete_node["data"])) + 1])
            delete_node["data"] = next_num
            delete_node = find_tree(root, next_num)
            parent = delete_node["parent"]
            if parent == None:
                node_direction = None
            elif parent["left"] == delete_node:
                node_direction = "left"
            else:
                node_direction = "right"
        else:
            if delete_node["left"]:
                parent[node_direction] = delete_node["left"]
                delete_node["left"]["parent"] = parent
            else:
                parent[node_direction] = delete_node["right"]
                delete_node["right"]["parent"] = parent
            break

    
def find_tree(root, target):
    focus_node = root

    while not focus_node == None:
        if focus_node["data"] == target:
            return focus_node
        elif focus_node["data"] < target:
            focus_node = focus_node["right"]
        else:
            focus_node = focus_node["left"]
    
    return None
    
def print_tree(root):
    print(" " + " ".join(get_inorder(root)))
    print(" " + " ".join(get_preorder(root)))
    
def main():
    
    n_line = int(input())
    input_list = [input() for i in range(n_line)]
    root = {"left":None, "right": None, "data":int(input_list[0].split()[1]), "parent": None}

    for line in input_list[1:]:
        if line == "print":
            print_tree(root)
        else:
            split_line = line.split()
            if split_line[0] == "insert":
                node = {"left":None, "right": None, "data":int(split_line[1]), "parent":None}
                insert(root, node)
            elif split_line[0] == "find":
                if find_tree(root, int(split_line[1])):
                    print("yes")
                else:
                    print("no")
            elif split_line[0] == "delete":
                delete_tree(root, int(split_line[1]))
        
        

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
N = int(input())
opr = []
for i in range(N):
    raw = input().strip().split(' ')
    if len(raw) == 2:
        opr.append([raw[0],int(raw[1])])
    else:
        opr.append([raw[0]])

tree = []
size = 0
root = -1

def insert(node,n):
    global tree
    global size

    if len(tree) == 0:
        tree.append([size,-1,-1,n])
        root = size
        size += 1
        return
    
    if tree[node][3] > n:
        if tree[node][1] == -1:
            tree.append([size,-1,-1,n])
            tree[node][1] = size
            size += 1
            return
        else:
            insert(tree[node][1],n)
    else:
        if tree[node][2] == -1:
            tree.append([size,-1,-1,n])
            tree[node][2] = size
            size+=1
            return
        else:
            insert(tree[node][2],n)

def print_sorted(node,start=False):
    flag_left = tree[node][1] != -1
    flag_right = tree[node][2] != -1
    s = start

    if(flag_left):
        start = not print_sorted(tree[node][1],start)
    sys.stdout.write(' %d' % tree[node][3])
        
    if(flag_right):
        start = not print_sorted(tree[node][2],False)
    return True
    
def print_mid(node,start=False):
    flag_left = tree[node][1] != -1
    flag_right = tree[node][2] != -1

    sys.stdout.write(' %d' % tree[node][3])
    if(flag_left):
        print_mid(tree[node][1])
    if(flag_right):
        print_mid(tree[node][2])
    flag_left

def find(node,parent,n):
    if tree[node][3] == n:
        return True 
    if tree[node][1] != -1:
        left = find(tree[node][1],node,n)
    else:
        left = False

    if tree[node][2] != -1:
        right = find(tree[node][2],node,n)
    else:
        right = False

    return left or right 


def find_replace(node,par):
    if tree[node][1] == -1 and tree[node][2] == -1:
        return node,par
    else:
        left = find_replace(tree[node][1],node)
        if left is not None:
            return left

        if tree[node][1] == -1:
            right = find_replace(tree[node][2],node)
            if right is not None:
                return right

        return None


def find_delete(node,parent,n):
    global root
    
    if tree[node][3] == n:
        num_child = 0
        if tree[node][1] !=-1:
            num_child += 1
        if tree[node][2] !=-1:
            num_child += 1
        
        if num_child == 0:
            if tree[parent][1] == node:
                tree[parent][1] = -1
            else:
                tree[parent][2] = -1
        elif num_child == 1:
            if tree[parent][1] == node:
                if tree[node][1] != -1:
                    tree[parent][1] = tree[node][1]
                else:
                    tree[parent][1] = tree[node][2]
            else:
                if tree[node][1] != -1:
                    tree[parent][2] = tree[node][1]
                else:
                    tree[parent][2] = tree[node][2]
        else:
            rep, par = find_replace(tree[node][2],node)

            tree[node][3] = tree[rep][3]
            if tree[par][1] == rep:
                tree[par][1] = -1
            else:
                tree[par][2] = -1
            
        return    


    if tree[node][1] != -1:
        left = find_delete(tree[node][1],node,n)
    else:
        left = False

    if tree[node][2] != -1:
        right = find_delete(tree[node][2],node,n)
    else:
        right = False

    return left or right 

tree = []
size = 0
root = 0
    
for idx,i in enumerate(opr):
    #print(idx)

    if i[0] == 'print':
        print_sorted(0,True)
        print()
        print_mid(0,True)
        print()
    if i[0] == 'insert':
        insert(0,i[1])
        #print(tree)
        #print_sorted(0,True)
        #print()
    if i[0] == 'find':
        ret = ['no','yes']
        print(ret[int(find(0,-1,i[1]))])
        #print(find(0,-1,i[1]))
    if i[0] == 'delete':
        #print('delete')
        find_delete(root,-1,i[1])

    #print_sorted(0,True)
    #print()
    #print(tree)

Submission status: Time Limit Exceeded

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

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

    def insert(self,x):
        if self.root == None:
            self.root = Node(x)
            return
        cur = self.root
        while True:
            if cur.value > x:
                if cur.left == None:
                    cur.left = Node(x)
                    cur.left.parent = cur
                    break
                cur = cur.left
            elif cur.value < x:
                if cur.right == None:
                    cur.right = Node(x)
                    cur.right.parent = cur
                    break
                cur = cur.right
            else:
                break

    def find(self,x):
        cur = self.root
        if cur == None:
            return None
        while True:
            if cur.value > x:
                if cur.left != None:
                    cur = cur.left
                else:
                    return None
            elif cur.value < x:
                if cur.right != None:
                    cur = cur.right
                else:
                    return None
            else:
                return cur

    def delete(self, x):
        n = self.find(x)
        if n == None:
            return
        else:
            self.delete_node(n)

    def delete_node(self, n):
        if n.left == None and n.right == None:
            if n.parent.left == n:
                n.parent.left = None
            elif n.parent.right == n:
                n.parent.right = None
        elif n.left == None:
            if n.parent.left == n:
                n.parent.left = n.right
                n.right.parent = n.parent
            elif n.parent.right == n:
                n.parent.right = n.right
                n.right.parent = n.parent
        elif n.right == None:
            if n.parent.left == n:
                n.parent.left = n.left
                n.left.parent = n.parent
            elif n.parent.right == n:
                n.parent.right = n.left
                n.left.parent = n.parent
        else:
            next_n = self.find_next(n)
            n.value = next_n.value
            self.delete_node(next_n)

    def find_next(self, n):
        x = n.right # always exists
        while x.left != None:
            x = x.left
        return x




    def mprint(self):
        print '',
        print ' '.join(map(str, self.inorder(self.root)))
        print '',
        print ' '.join(map(str, self.preorder(self.root)))

    def inorder(self, cur):
        ret = []
        if cur.left != None:
            ret += self.inorder(cur.left)
        ret.append(cur.value)
        if cur.right != None:
            ret += self.inorder(cur.right)
        return ret

    def preorder(self, cur):
        ret = []
        ret.append(cur.value)
        if cur.left != None:
            ret += self.preorder(cur.left)
        if cur.right != None:
            ret += self.preorder(cur.right)
        return ret



m = int(raw_input())
tree = BST()
commands = []
for _ in range(m):
    line = raw_input()
    if line[0] == 'i':
        num = int(line.split(' ')[1])
        commands.append(('insert', num))
    elif line[0] == 'p':
        commands.append(('print', '-1'))
    elif line[0] == 'f':
        num = int(line.split(' ')[1])
        commands.append(('find', num))
    elif line[0] == 'd':
        num = int(line.split(' ')[1])
        commands.append(('delete', num))
    else:
        raise Exception("Unknown command")

for cmd, num in commands:
    if cmd == 'insert':
        tree.insert(num)
    elif cmd == 'print':
        tree.mprint()
    elif cmd == 'find':
        if tree.find(num):
            print 'yes'
        else:
            print 'no'
    elif cmd == 'delete':
        tree.delete(num)

Submission status: Time Limit Exceeded

Solution code:
class Tree:
    def __init__(self, orders):
        self.root = None
        for order in orders:
            if len(order) == 1:
                self.inorder_print()
                self.preorder_print()
            else:
                if len(order[0]) == 4:
                    self.find(int(order[1]))
                else:
                    self.insert(int(order[1]))

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

    def find(self, key):
        x = self.root
        while True:
            if key == x.key:
                print('yes')
            elif key < x.key:
                if not x.left:
                    x = x.left
                else:
                    print('no')
            else:
                if not x.right:
                    x = x.right
                else:
                    print('no')

    def delete(self, key):
        z = self.root
        while z.key != key:
            if key < z.key:
                z = z.left
            else:
                z = z.right

        if not z.left or not z.right:
            y = z
        else:
            y = self.get_successor(z)

        if y.left:
            x = y.left
        else:
            x = y.right

        if x:
            x.parent = y.parent

        if not y.parent:
            self.root = x
        elif y == y.parent.left:
            y.parent.left = x
        else:
            y.parent.right = x

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

        del (y)

    def get_successor(self, x):
        if x.right:
            return self.get_minimum(x.right)

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

    def get_minimum(self, x):
        while x.left:
            x = x.left
        return x

    def inorder_print(self):
        self.root.inorder_print()
        print()

    def preorder_print(self):
        self.root.preorder_print()
        print()


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

    def inorder_print(self):
        if self.left:
            self.left.inorder_print()
        print(' {}'.format(self.key), end='')
        if self.right:
            self.right.inorder_print()

    def preorder_print(self):
        print(' {}'.format(self.key), end='')
        if self.left:
            self.left.preorder_print()
        if self.right:
            self.right.preorder_print()


if __name__ == '__main__':
    import sys
    m = int(input())
    orders = [line.strip().split() for line in sys.stdin]
    Tree(orders)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 19 22:51:44 2018

@author: maezawa
"""

class node():
    def __init__(self, key, parent=None, right=None, left=None):
        self.key = key
        self.parent = parent
        self.right = right
        self.left = left
        
def insert(z):
    global root
    y = None
    x = root
    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
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z  
    #inorder(root)
    
def find(x, k):
    while x != None and k != x.key:
        if k < x.key:
            x = x.left
        else:
            x = x.right
    return x

def delete_node(z):
    global root
    #x = node(None)
    if z.left == None or z.right == None:
        y = z
    else:
        y = get_successor(z)
        
    if y.left != None:
        x = y.left
    else:
        x = y.right
    if x != None:
        x.parent = y.parent

    if y.parent == None:
        root = x
        #print('deleteing {}, settting the root for {}'.format(y.key,x))
    elif y == y.parent.left:
        y.parent.left = x
    else:
        y.parent.right = x
    if y != z:
        z.key = y.key
        
def get_successor(x):
    if x.right != None:
        return get_min(x.right)
    y = x.parent
    while y != None and x == y.right:
        x = y
        y = y.parent
    return y

def get_min(x):
    while x.left != None:
        x = x.left
    return x
        
def inorder(u):
    if u == None:
        return
    inorder(u.left)
    print(' {}'.format(u.key), end = '')
    inorder(u.right)
    
def preorder(u):
    if u == None:
        return
    print(' {}'.format(u.key), end = '')
    preorder(u.left)
    preorder(u.right)
    
root = None

n = int(input())
for i in range(n):
    q = list(input().split())
    if q[0] == 'insert':
        z = node(int(q[1]))
        insert(z)
    elif q[0] == 'find':
        if find(root, int(q[1])):
            print('yes')
        else:
            print('no')
    elif q[0] == 'delete':
            z = find(root, int(q[1]))
            delete_node(z)
    elif q[0] == 'print':
        inorder(root)
        print()
        preorder(root)
        print()
    #print('root:{}'.format(root.key))

Submission status: Accepted

Solution code:
#coding:utf-8

class MakeTree():
    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,value):
    y = None
    x = root
    z = MakeTree(value)

    while x != None:
        y = x
        if x.key > z.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 Find(u, target):
    y = None
    x = u
    while x != None and target != x.key:
        y = x
        if x.key > target:
            x = x.l
        else:
            x = x.r
    return x


def Delete(u, 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:
        root = x
    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


def inParse(u):
    if u == None:
        return
    inParse(u.l)
    global inParseList
    inParseList.append(u.key)
    inParse(u.r)

def preParse(u):
    if u == None:
        return
    global preParseList
    preParseList.append(u.key)
    preParse(u.l)
    preParse(u.r)


root = None       
n = int(input())
inParseList = []
preParseList = []
for i in range(n):
    order = list(input().split())
    if order[0] == "insert":
        root = Insert(root, int(order[1]))
        
    elif order[0] == "print":
        inParse(root)
        preParse(root)
        print(" " + " ".join([str(i) for i in inParseList]))
        print(" " + " ".join([str(i) for i in preParseList]))
        preParseList = []
        inParseList = []
        
    elif order[0] == "find":
        x = Find(root, int(order[1]))
        if x == None:
            print("no")
        else:
            print("yes")
    else:
        x = Find(root, int(order[1]))
        Delete(root, x)

Submission status: Accepted

Solution code:
import sys, os
from io import StringIO

class BinaryTree:

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


    def __init__(self):
        self.root = None
        self.output = StringIO()

    def insert(self, key):
        if self.root is None:
            self.root = self.Node(key)
        else:
            root = self.root
            temp = None
            while True:
                temp = root
                if key > root.key:
                    root = root.right
                    if root is None:
                        temp.right = self.Node(key)
                        n = temp.right
                        n.parent = temp
                        break
                else:
                    root = root.left
                    if root is None:
                        temp.left = self.Node(key)
                        n = temp.left
                        n.parent = temp
                        break

    def ini_print_inorder(self):
        self.output = StringIO()
        self.print_inorder(self.root)
        return self.output.getvalue()

    def ini_print_preorder(self):
        self.output = StringIO()
        self.print_preorder(self.root)
        return self.output.getvalue()

    def print_inorder(self, node):
        if node is not None:
            self.print_inorder(node.left)
            print(node.key, end = " ", file = self.output)
            self.print_inorder(node.right)

    def print_preorder(self, node):
        if node is not None:
            print(node.key, end = " ", file = self.output)
            self.print_preorder(node.left)
            self.print_preorder(node.right)

    def test_insert(self, keys):
        for k in keys:
            self.insert(k)

    def ini_find(self, key):
        print(self.find(key))

    def find(self, key):
        root = self.root
        while root is not None:
            if key == root.key:
                return "yes"
            elif key < root.key:
                root = root.left
            else:
                root = root.right
        return "no"

    def get_successor(self, node):
        parent = node
        while True:
            node = node.left
            if node is None:
                return parent, parent.parent
            parent = node
        return None

    def delete(self, key):
        root = self.root
        temp = root
        act = ""
        while root is not None:
            if key == root.key:
                # print(root.key, root.left, root.right, root.parent)
                rest = None
                new_leaf = None
                if root.left is None:
                    new_leaf = root.right
                elif root.right is None:
                    new_leaf = root.left
                else:
                    new_leaf, new_leaf_parent = self.get_successor(root.right)
                    rest = 1
                    rest_left = root.left
                    rest_right = root.right
                    if new_leaf == rest_right:
                        rest_right = None
                    # print(rest_left.key, new_leaf.key, new_leaf_parent.key)
                if act != "":
                    setattr(temp, act, new_leaf)
                    # print(new_leaf)
                    if new_leaf is not None:
                        new_node = getattr(temp, act)
                        setattr(new_node, "parent", temp)
                        # print(act, temp.key, key, new_leaf.key, new_node.parent.key)
                else:
                    self.root = new_leaf
                if rest is not None:
                    temp = getattr(temp, act)
                    if rest_right is not None:
                        setattr(temp, "right", rest_right)
                        setattr(rest_right, "parent", temp)
                    setattr(temp, "left", rest_left)
                    setattr(rest_left, "parent", temp)
                    setattr(new_leaf_parent, "left", None)
                    # print("00", temp.key, new_leaf.key, new_leaf.parent.key, new_leaf_parent.key)
                return
            else:
                temp = root
                if key < root.key:
                    root = root.left
                    act = "left"
                else:
                    root = root.right
                    act = "right"

b = BinaryTree()
length = int(input())
for _ in range(length):
    comm = input()
    if comm[0] == "i":
        com, num = comm.split(" ")
        b.insert(int(num))
    elif comm[0] == "p":
        print(" ", end = "")
        print((b.ini_print_inorder())[:-1])
        print(" ", end = "")
        print(b.ini_print_preorder()[:-1])
    elif comm[0] == "f":
        com, num = comm.split(" ")
        b.ini_find(int(num))
    else:
        com, num = comm.split(" ")
        b.delete(int(num))

Submission status: Accepted

Solution code:
import sys, os
from io import StringIO

class BinaryTree:

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


    def __init__(self):
        self.root = None
        self.output = StringIO()

    def insert(self, key):
        if self.root is None:
            self.root = self.Node(key)
        else:
            root = self.root
            temp = None
            while True:
                temp = root
                if key > root.key:
                    root = root.right
                    if root is None:
                        temp.right = self.Node(key)
                        n = temp.right
                        n.parent = temp
                        break
                else:
                    root = root.left
                    if root is None:
                        temp.left = self.Node(key)
                        n = temp.left
                        n.parent = temp
                        break

    def ini_print_inorder(self):
        self.output = StringIO()
        self.print_inorder(self.root)
        return self.output.getvalue()

    def ini_print_preorder(self):
        self.output = StringIO()
        self.print_preorder(self.root)
        return self.output.getvalue()

    def print_inorder(self, node):
        if node is not None:
            self.print_inorder(node.left)
            print(node.key, end = " ", file = self.output)
            self.print_inorder(node.right)

    def print_preorder(self, node):
        if node is not None:
            print(node.key, end = " ", file = self.output)
            self.print_preorder(node.left)
            self.print_preorder(node.right)

    def test_insert(self, keys):
        for k in keys:
            self.insert(k)

    def ini_find(self, key):
        print(self.find(key))

    def find(self, key):
        root = self.root
        while root is not None:
            if key == root.key:
                return "yes"
            elif key < root.key:
                root = root.left
            else:
                root = root.right
        return "no"

    def get_successor(self, node):
        parent = node
        while True:
            node = node.left
            if node is None:
                return parent, parent.parent
            parent = node
        return None

    def delete(self, key):
        root = self.root
        temp = root
        act = ""
        while root is not None:
            if key == root.key:
                # print(root.key, root.left, root.right, root.parent)
                rest = None
                new_leaf = None
                if root.left is None:
                    new_leaf = root.right
                elif root.right is None:
                    new_leaf = root.left
                else:
                    new_leaf, new_leaf_parent = self.get_successor(root.right)
                    rest = 1
                    rest_left = root.left
                    rest_right = root.right
                    if new_leaf == rest_right:
                        rest_right = None
                    # print(rest_left.key, new_leaf.key, new_leaf_parent.key)
                if act != "":
                    setattr(temp, act, new_leaf)
                    # print(new_leaf)
                    if new_leaf is not None:
                        new_node = getattr(temp, act)
                        setattr(new_node, "parent", temp)
                        # print(act, temp.key, key, new_leaf.key, new_node.parent.key)
                else:
                    self.root = new_leaf
                if rest is not None:
                    temp = getattr(temp, act)
                    if rest_right is not None:
                        setattr(temp, "right", rest_right)
                        setattr(rest_right, "parent", temp)
                    setattr(temp, "left", rest_left)
                    setattr(rest_left, "parent", temp)
                    setattr(new_leaf_parent, "left", None)
                    # print("00", temp.key, new_leaf.key, new_leaf.parent.key, new_leaf_parent.key)
                return
            else:
                temp = root
                if key < root.key:
                    root = root.left
                    act = "left"
                else:
                    root = root.right
                    act = "right"

b = BinaryTree()
length = int(input())
for comm in sys.stdin:
    if comm[0] == "i":
        com, num = comm.split(" ")
        b.insert(int(num))
    elif comm[0] == "p":
        print(" ", end = "")
        print((b.ini_print_inorder())[:-1])
        print(" ", end = "")
        print(b.ini_print_preorder()[:-1])
    elif comm[0] == "f":
        com, num = comm.split(" ")
        b.ini_find(int(num))
    else:
        com, num = comm.split(" ")
        b.delete(int(num))