Problem:

Binary Search Tree III

Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II.

  
insert  $k$: Insert a node containing $k$ as key into $T$.

  
find $k$: Report whether $T$ has a node containing $k$. 

  
delete $k$: Delete a node containing $k$.

  
print: Print the keys of the binary search tree by inorder tree walk and  preorder tree walk respectively.

The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases:

 If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$).

 If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent.

 If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key.

Input

   In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given.

Output

For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not.

  In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key

Constraints

   
The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

  
$-2,000,000,000 \leq key \leq 2,000,000,000$

  
The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

18
insert 8
insert 2
insert 3
insert 7
insert 22
insert 1
find 1
find 2
find 3
find 4
find 5
find 6
find 7
find 8
print
delete 3
delete 7
print

Sample Output 1

yes
yes
yes
no
no
no
yes
yes
 1 2 3 7 8 22
 8 2 1 3 7 22
 1 2 8 22
 8 2 1 22

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.



Sample input:
18
insert 8
insert 2
insert 3
insert 7
insert 22
insert 1
find 1
find 2
find 3
find 4
find 5
find 6
find 7
find 8
print
delete 3
delete 7
print


Sample output:
yes
yes
yes
no
no
no
yes
yes
 1 2 3 7 8 22
 8 2 1 3 7 22
 1 2 8 22
 8 2 1 22

Submission status: Accepted

Solution code:
import sys
 
NIL = -1
 
class Node:
    def __init__(self, key):
        self.key = key
        self.parent = NIL
        self.left = NIL
        self.right = NIL
 
class Tree:
    def __init__(self):
        self.root = NIL
 
    def insert(self, z):
        y = NIL
        x = self.root
 
        while x != NIL:
            y = x
 
            if z.key < x.key:
                x = x.left
            else:
                x = x.right
 
        z.parent = y
 
        if y == NIL:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z

    def find(self, value, node):
        if node == NIL:
            return False
        elif node.key == value:
            return True
        elif value < node.key:
            # print('go to left')
            return self.find(value, node=node.left)
        else:
            # print('go to right')
            return self.find(value, node=node.right)

    def delete(self, value, node):
        if node == NIL:
            return None
        elif value < node.key:
            self.delete(value, node.left)
        elif value > node.key:
            self.delete(value, node.right)
        else:
            check = (node.left != NIL) + (node.right != NIL)

            if check == 0:
                if node.parent.left != NIL and node.parent.left.key == value:
                    node.parent.left = NIL
                else:
                    node.parent.right = NIL

            elif check == 1:
                if node.left != NIL:
                    child = node.left
                else:
                    child = node.right

                if node.parent.left != NIL and node.parent.left.key == value:
                    node.parent.left = child
                    child.parent = node.parent
                else:
                    node.parent.right = child
                    child.parent = node.parent

            else:
                jisetu = node.right

                while jisetu.left != NIL:
                    jisetu = jisetu.left

                node.key = jisetu.key
                self.delete(jisetu.key, jisetu)

    def inorder_walk(self, node):
        if node == NIL:
            return None
 
        if node.left != NIL:
            self.inorder_walk(node=node.left)
 
        print(' ' + str(node.key), end='')
 
        if node.right != NIL:
            self.inorder_walk(node=node.right)
 
    def preorder_walk(self, node):
        if node == NIL:
            return None
 
        print(' ' + str(node.key), end='')
 
        if node.left != NIL:
            self.preorder_walk(node=node.left)
 
        if node.right != NIL:
            self.preorder_walk(node=node.right)
 
    def show(self):
        self.inorder_walk(self.root)
        print()
        self.preorder_walk(self.root)
        print()
 
 
n = int(sys.stdin.readline())
T = Tree()
 
for i in range(n):
    line = sys.stdin.readline().split()

    if len(line) == 1:
        T.show()
    elif line[0] == 'insert':
        key = int(line[1])
        T.insert(Node(key))
    elif line[0] == 'find':
        key = int(line[1])
        print('yes' if T.find(key, T.root) else 'no')
    else:
        key = int(line[1])
        T.delete(key, T.root)

Submission status: Accepted

Solution code:
import sys

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

    def prewalk(self):
        nodeList = [self.key]
        if self.left:
            nodeList += self.left.prewalk()
        if self.right:
            nodeList += self.right.prewalk()
        return nodeList

    def inwalk(self):
        nodeList = []
        if self.left:
            nodeList += self.left.inwalk()
        nodeList += [self.key]
        if self.right:
            nodeList += self.right.inwalk()
        return nodeList

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

    def insert(self, key):
        Nz = Node(key)
        Ny = None  # ???????£?
        Nx = self.root
        while Nx:
            Ny = Nx
            if Nz.key < Ny.key:
                Nx = Nx.left
            else:
                Nx = Nx.right
        Nz.parent = Ny
        if Ny == None:
            self.root = Nz
        elif Nz.key < Ny.key:
            Ny.left = Nz
        else:
            Ny.right = Nz

    def find(self, key):
        Nx = self.root
        while Nx and Nx.key != key:
            if key < Nx.key:
                Nx = Nx.left
            else:
                Nx = Nx.right
        return Nx

    def delete(self, key):
        Nz = self.find(key)
        # Ny: the node to be deleted
        if Nz.left and Nz.right:
            Ny = self.successor(Nz)
        else:
            Ny = Nz
        # Nx: y's child
        if Ny.left:
            Nx = Ny.left
        else:
            Nx = Ny.right

        if Nx:
            Nx.parent = Ny.parent

        if Ny.parent == None:
            self.root = Nx
        elif Ny == Ny.parent.left:
            Ny.parent.left = Nx
        else:
            Ny.parent.right = Nx

        if Ny != Nz:
            Nz.key = Ny.key

    def successor(self, Nx):
        if Nx.right:
            return self.minimum(Nx.right)

        Ny = Nx.parent
        while Ny != None and Nx == Ny.right:
            Nx = Ny
            Ny = Ny.parent
        return Ny

    def minimum(self, Nx):
        while Nx.left:
            Nx = Nx.left
        return Nx

    def print(self):
        print('', ' '.join(map(str, self.root.inwalk())))
        print('', ' '.join(map(str, self.root.prewalk())))

tree = Tree()

n = sys.stdin.readline()
for line in sys.stdin:
    if line[0] == 'i':
        tree.insert(int(line.split()[1]))
    elif line[0] == 'f':
        if tree.find(int(line.split()[1])):
            print('yes')
        else:
            print('no')
    elif line[0] == 'd':
        tree.delete(int(line.split()[1]))
    else:
        tree.print()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

import random
import sys
import os


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

    def __str__(self):
        if self.root == None:
            return None
        else:
            return "TODO"

    def print_inorder(self):
        self.inorder_list = []
        self.__inorder(self.root)
        return self.inorder_list

    def __inorder(self, node):
        """
        :param node: Node
        :return:
        """
        if node is None:
            return
        else:
            self.__inorder(node.left)
            self.inorder_list.append(node.key)
            self.__inorder(node.right)

    def print_preorder(self):
        self.preorder_list = []
        self.__preorder(self.root)
        return self.preorder_list

    def __preorder(self, node):
        """
        :param node: Node
        :return:
        """
        if node is None:
            return
        else:
            self.preorder_list.append(node.key)
            self.__preorder(node.left)
            self.__preorder(node.right)

    def insert(self, node):
        """
        :param node: Node
        :return:
        """
        if self.root is None:
            self.root = node
        else:
            x = self.root
            parent_candidate = x

            while x is not None:
                parent_candidate = x
                if x.key > node.key:
                    x = x.left
                else:
                    x = x.right

            # child to parent link
            x = node
            x.parent = parent_candidate

            # parent to child link
            if x.key < x.parent.key:
                x.parent.left = x
            else:
                x.parent.right = x

    def find(self, value):
        """
        :param value:
        :rtype: Node
        :return:
        """
        x = self.root
        while x is not None and x.key != value:
            if x.key > value:
                x = x.left
            else:
                x = x.right
        return x

    def delete(self, value):
        found_node = self.find(value)
        if found_node is None:
            print("value is nothing")
        else:
            # has no child
            if found_node.is_leaf():
                # delete link from parent
                # print(found_node.parent.left.key)
                # print(found_node.key)

                if found_node.parent.left is not None and found_node.parent.left.key == found_node.key:
                    found_node.parent.left = None
                else:
                    found_node.parent.right = None
            else:
                # has one child
                if found_node.has_one_child():
                    one_child = found_node.get_one_child()

                    # change link to parent
                    one_child.parent = found_node.parent

                    # chagne link from parent
                    if found_node.parent.left == found_node:
                        found_node.parent.left = one_child
                    else:
                        found_node.parent.right = one_child

                # has two child
                else:
                    next_section_point = found_node.get_next_section_point()
                    # ?¬???????????????????????????????????????????????¬?????????????????????? p217
                    # ????????????
                    key = next_section_point.key
                    self.delete(next_section_point.key)
                    found_node.key = key


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

    def has_one_child(self):
        if self.left is None and self.right is not None:
            return True
        elif self.left is not None and self.right is None:
            return True
        else:
            return False

    def get_one_child(self):
        if not self.has_one_child():
            return None
        else:
            if self.left is not None:
                return self.left
            else:
                return self.right

    def get_next_section_point(self):
        """?¬??????????????????????"""

        # ????????????????????´???
        if self.right is not None:
            return self.right.get_minimum()
        # ???????????????????????´???????¬???????????????´?????????
        else:
            # ?
            return self.parent

    def is_leaf(self):
        if self.left is None and self.right is None:
            return True
        else:
            return False

    def get_minimum(self):
        if self.left is None:
            return self
        else:
            return self.left.get_minimum()

tree = Tree()
s = input()
n = int(s)
for _ in range(n):
    s = input()
    if 'insert' in s:
        value = int(s.split(" ")[-1])
        node = Node(value)
        tree.insert(node)

    if 'print' in s:
        in_list = tree.print_inorder()
        in_list = map(str, in_list)
        print(' ' + ' '.join(in_list))

        pre_list = tree.print_preorder()
        pre_list = map(str, pre_list)
        print(' ' + ' '.join(pre_list))

    if 'find' in s:
        value = int(s.split(" ")[-1])
        node = tree.find(value)
        if node is None:
            print('no')
        else:
            print('yes')

    if 'delete' in s:
        value = int(s.split(" ")[-1])
        tree.delete(value)

Submission status: Accepted

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

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

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

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

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

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

  def delete(self, node):
    if node.left and node.right:
      m = self.find_minimum(node.right)
      node.key = m.key
      self.delete(m)
    elif node.left:
      self.update(node, node.left)
    elif node.right:
      self.update(node, node.right)
    else:
      self.update(node, None)

  def update(self, node, new_node):
    if node.key < node.p.key:
      node.p.left = new_node
    else:
      node.p.right = new_node
    if new_node:
      new_node.p = node.p

def print_inorder(node):
  if node is None: return
  print_inorder(node.left)
  print(" {}".format(node.key), end="")
  print_inorder(node.right)

def print_preorder(node):
  if node is None: return
  print(" {}".format(node.key), end="")
  print_preorder(node.left)
  print_preorder(node.right)

T = BinarySearchTree()
for i in range(int(input())):
  params = input().split()
  if params[0] == "insert":
    T.insert(Node(int(params[1])))
  elif params[0] == "find":
    if T.find(int(params[1])):
      print("yes")
    else:
      print("no")
  elif params[0] == "delete":
    node = T.find(int(params[1]))
    if node: T.delete(node)
  elif params[0] == "print":
    print_inorder(T.root)
    print("")
    print_preorder(T.root)
    print("")

Submission status: Accepted

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

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

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

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

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

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

  def delete(self, node):
    if node.left and node.right:
      m = self.find_minimum(node.right)
      node.key = m.key
      self.delete(m)
    elif node.left:
      self.update(node, node.left)
    elif node.right:
      self.update(node, node.right)
    else:
      self.update(node, None)

  def update(self, node, new_node):
    if node.p is None:
      self.root = new_node
      if new_node: new_node.p = None
      return

    if node.key < node.p.key:
      node.p.left = new_node
    else:
      node.p.right = new_node
    if new_node:
      new_node.p = node.p

def print_inorder(node):
  if node is None: return
  print_inorder(node.left)
  print(" {}".format(node.key), end="")
  print_inorder(node.right)

def print_preorder(node):
  if node is None: return
  print(" {}".format(node.key), end="")
  print_preorder(node.left)
  print_preorder(node.right)

T = BinarySearchTree()
for i in range(int(input())):
  params = input().split()
  if params[0] == "insert":
    T.insert(Node(int(params[1])))
  elif params[0] == "find":
    if T.find(int(params[1])):
      print("yes")
    else:
      print("no")
  elif params[0] == "delete":
    node = T.find(int(params[1]))
    if node: T.delete(node)
  elif params[0] == "print":
    print_inorder(T.root)
    print("")
    print_preorder(T.root)
    print("")

Submission status: Accepted

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

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

    def find(self, key):
        x = self.root
        while x and key != x.key:
            if key < x.key:
                x = x.left
            else:
                x = x.right
        return x

    def getSuccessor(self, x):
        if x.right is not None:
            return self.getMinimum(x.right)

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

    def getMinimum(self, x):
        while x.left is not None:
            x = x.left
        return x

    def delete(self, key):
        #??????????±????y???????´?
        z = self.find(key)
        if z.left is None or z.right is None:
            y = z
        else:
            y = self.getSuccessor(z)

        # y??????x????????????
        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:
            self.root = x
        elif y == y.parent.left:
            y.parent.left = x
        else:
            y.parent.right = x

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


    def show(self):
        print(" ", end="")
        print(*list(map(str, self.root.inwalk())))
        print(" ", end="")
        print(*list(map(str, self.root.prewalk())))


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

    def prewalk(self):
        nodeList = [self.key]
        if self.left:
            nodeList += self.left.prewalk()
        if self.right:
            nodeList += self.right.prewalk()
        return nodeList

    def inwalk(self):
        nodeList = []
        if self.left:
            nodeList += self.left.inwalk()
        nodeList += [self.key]
        if self.right:
            nodeList += self.right.inwalk()
        return nodeList


tree = Tree()
n = int(input())
for i in range(n):
    cmd = list(input().split())
    if cmd[0] == 'insert':
        tree.insert(int(cmd[1]))
    elif cmd[0] == 'find':
        if tree.find(int(cmd[1])):
            print("yes")
        else:
            print("no")
    elif cmd[0] == 'print':
        tree.show()
    elif cmd[0] == 'delete':
        tree.delete(int(cmd[1]))

Submission status: Accepted

Solution code:
#BinarySearchTree
class TreeNode():
    def __init__(self):
        self.key = None
        self.parent = None
        self.left = None
        self.right = None
    def inoder(self):
        r=[]
        if self.left:
            r += self.left.inoder()
        r += [self.key]
        if self.right:
            r += self.right.inoder()
        return r
 
    def preoder(self):
        r = [self.key]
        if self.left:
            r += self.left.preoder()
        if self.right:
            r += self.right.preoder()
        return r
 
class BinaryTree():
    def __init__(self):
        self.root = None
 
    def insert(self, z):
        y = None
        x = self.root
        while x != None:
            y = x
            if z.key < x.key:
                x = x.left
            else:
                x = x.right
        z.parent = y
        if y == None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z
 
    def show(self):
        x = self.root
        print(" " + " ".join(map(str, self.root.inoder())))
        print(" " + " ".join(map(str, self.root.preoder())))
 
    def find(self, key):
        currentNode = self.root
        while currentNode:
            if key == currentNode.key:
                return currentNode
            else:
                if key < currentNode.key:
                    currentNode = currentNode.left
                else:
                    currentNode = currentNode.right
        return False
    def next(self, key):
        return self.min(key.right)
    def min (self, key):
        while key.left is not None:
           key = key.left
        return key
     
    def delete(self, key):
        z = self.find(key)
        if z == False: return
        if z.left and z.right:
            y = self.next(z)
        else:
            y = z
            if z == self.root:
                self.root = None
         
        if z.left:
            x = y.left
        else:
            x = y.right

        if x:
            x.parent = y.parent
        if y.parent is None:
            self.root = x
        elif y == y.parent.left:
            y.parent.left = x
        else:
            y.parent.right = x
        if y != z:
            z.key = y.key

n = int(input())
Tree = BinaryTree()
for i in range(n):
    L = input().split()
    if L[0] == "insert":
        Node = TreeNode()
        Node.key = int(L[1])
        Tree.insert(Node)
    if L[0] =="print":
        Tree.show()
    if L[0] =="find":
        if Tree.find(int(L[1])) == False:
            print("no")
        else:
            print("yes")
    if L[0] =="delete":
        Tree.delete(int(L[1]))

Submission status: Accepted

Solution code:
import sys

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None
    
    def insert(node, x):
        if node == None:
            return Node(x)
#==============================================================================
#         elif x == node.data:
#             return node
#==============================================================================
        elif x < node.data:
            node.left = Node.insert(node.left, x)
        else:
            node.right = Node.insert(node.right, x)
        return node
    
    def find(node, x):
        if node.data == x:
            return True
        elif node.left != None and node.data > x:
            return Node.find(node.left, x)
        elif node.right != None and node.data < x:
            return Node.find(node.right, x)
        else:
            return False
        
    def delete(node, x):
        if node.data == x:
            if (node.left == None) and (node.right == None):
                return None
            elif node.left == None:
                return node.right
            elif node.right == None:
                return node.left
            else:
                #????????????
                node.data = Node.serch_min(node.right)
                node.right = Node.delete_min(node.right)
                return node
        elif node.data > x:
            node.left =  Node.delete(node.left, x)
        else:
            node.right = Node.delete(node.right, x)
        return node
        
    def serch_min(node):
        if node.left != None:
            return Node.serch_min(node.left)
        else:
            return node.data
    
    def delete_min(node):
        if node.left == None:
            return node.right
        else:
            node.left = Node.delete_min(node.left)
            return node    
        
    def inorder_print(node):
#==============================================================================
#         if node.left != None:
#             Node.inorder_print(node.left)
#         print("",node.data,  end="")
#         if node.right != None:
#             Node.inorder_print(node.right)
#==============================================================================
        s = ""
        if node.left != None:
            s += Node.inorder_print(node.left)
        s += " " + str(node.data)
        if node.right != None:
            s += Node.inorder_print(node.right)
        return s
    def preorder_print(node):
#==============================================================================
#         print("",node.data,  end="")
#         if node.left != None:
#             Node.preorder_print(node.left)
#         if node.right != None:
#             Node.preorder_print(node.right)
#==============================================================================
        s = ""
        s += " " + str(node.data)
        if node.left != None:
            s += Node.preorder_print(node.left)    
        if node.right != None:
            s += Node.preorder_print(node.right)
        return s
class BinaryTree:
    def __init__(self):
        self.root = None
    
    def insert(self, x):
        self.root = Node.insert(self.root, x)

    def find(self, x):
        if Node.find(self.root, x):
            print("yes")
        else:
            print("no")
            
    def delete(self, x):
        self.root = Node.delete(self.root, x)
        
    def print_tree(self):
#==============================================================================
#         Node.inorder_print(self.root)
#         print()
#         Node.preorder_print(self.root)
#         print()
#==============================================================================
        s = Node.inorder_print(self.root)
        print(s)
        s = Node.preorder_print(self.root)
        print(s)
def main():
    T = BinaryTree()
    m = int(sys.stdin.readline())
    for i in range(m):
        s = sys.stdin.readline().strip()
        if(s == "print"):
            T.print_tree()
        elif s.split()[0] == "find":
            T.find(int(s.split()[1]))
        elif s.split()[0] == "delete":
            T.delete(int(s.split()[1]))
        else:
            z = int(s.split()[1])
            T.insert(z)
        #print(s)
        #T.print_tree()

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys


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

    def preorder(self):
        nodeList = [self.key]
        if self.left:
            nodeList += self.left.preorder()
        if self.right:
            nodeList += self.right.preorder()
        return nodeList

    def inorder(self):
        nodeList = []
        if self.left:
            nodeList += self.left.inorder()
        nodeList += [self.key]
        if self.right:
            nodeList += self.right.inorder()
        return nodeList


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

    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 y is None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z

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

    def delete(self, key):
        z = self.find(key)
        if z is not None:
            if z.left is not None and z.right is not None:
                temp = self.getMinimum(z.right)
                self.delete(temp.key)
                z.key = temp.key
            elif z.left is not None:
                if z.parent is None:
                    self.root = z.left
                    z.left.parent = None
                else:
                    if z.parent.left is z:
                        z.parent.left = z.left
                    else:
                        z.parent.right = z.left
                    z.left.parent = z.parent
            elif z.right is not None:
                if z.parent is None:
                    self.root = z.right
                    z.right.parent = None
                else:
                    if z.parent.left is z:
                        z.parent.left = z.right
                    else:
                        z.parent.right = z.right
                    z.right.parent = z.parent
            else:
                if z.parent is None:
                    self.root = None
                else:
                    if z.parent.left is z:
                        z.parent.left = None
                    else:
                        z.parent.right = None

    def getMinimum(self, node):
        while node.left is not None:
            node = node.left
        return node

    def print(self):
        print(" " + " ".join(map(str, self.root.inorder())))
        print(" " + " ".join(map(str, self.root.preorder())))


if __name__ == "__main__":
    tree = BinaryTree()
    n = int(sys.stdin.readline())
    for inp in sys.stdin.readlines():
        inp = inp.split()
        if inp[0] == "insert":
            tree.insert(int(inp[1]))
        elif inp[0] == "find":
            if tree.find(int(inp[1])) is None:
                print("no")
            else:
                print("yes")
        elif inp[0] == "delete":
            tree.delete(int(inp[1]))
        else:
            tree.print()