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:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None


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

    def insert(self, val):
        if not self.root:
            self.root = TreeNode(val)
        else:
            parent = None
            cur = self.root
            while cur:
                parent = cur
                if val < cur.val:
                    cur = cur.left
                elif cur.val < val:
                    cur = cur.right

            if val < parent.val:
                parent.left = TreeNode(val)
            elif parent.val < val:
                parent.right = TreeNode(val)

    def find(self, val):
        if not self.root:
            return False
        else:
            cur = self.root
            while cur:
                if val < cur.val:
                    cur = cur.left
                elif cur.val < val:
                    cur = cur.right
                else:
                    return True
            return False

    def remove(self, val):
        self._remove(self.root, val, None)

    def _remove(self, node, val, parent):
        if not node:
            return
        elif val < node.val:
            self._remove(node.left, val, node)
        elif node.val < val:
            self._remove(node.right, val, node)
        else:
            if node.left and node.right:
                # Find min value from right sub-tree
                cur = node.right
                while cur.left:
                    cur = cur.left
                node.val = cur.val
                self._remove(node.right, cur.val, node)
            elif node.left:
                if parent.left == node:
                    parent.left = node.left
                elif parent.right == node:
                    parent.right = node.left
            elif node.right:
                if parent.left == node:
                    parent.left = node.right
                elif parent.right == node:
                    parent.right = node.right
            else:
                if parent.left == node:
                    parent.left = None
                elif parent.right == node:
                    parent.right = None


def inorder(node):
    if node:
        res = []
        res += inorder(node.left)
        res.append(node.val)
        res += inorder(node.right)
        return res
    else:
        return []


def preorder(node):
    if node:
        res = [node.val]
        res += preorder(node.left)
        res += preorder(node.right)
        return res
    else:
        return []


if __name__ == '__main__':
    n = int(input())
    bst = BinarySearchTree()
    for _ in range(n):
        cmd, *num = input().split()
        if cmd == 'insert':
            bst.insert(int(num[0]))
        elif cmd == 'find':
            if bst.find(int(num[0])):
                print('yes')
            else:
                print('no')
        elif cmd == 'delete':
            bst.remove(int(num[0]))
        else:
            for x in inorder(bst.root):
                print(f' {x}', end='')
            print()
            for x in preorder(bst.root):
                print(f' {x}', end='')
            print()

Submission status: Accepted

Solution code:
class TreeNode:
  def __init__(self, val):
    self.val = val
    self.left = None
    self.right = None

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

  def insert(self, val):
    node = TreeNode(val)
    if self.root is None: 
      self.root = node
      return

    cur_parent = None
    cur_root = self.root

    while cur_root is not None:
      cur_parent = cur_root
      if val > cur_root.val:
        cur_root = cur_root.right
      else:
        cur_root = cur_root.left

    if val > cur_parent.val:
      cur_parent.right = node
    else:
      cur_parent.left = node

  def find(self, val):
    cur_node = self.root

    while cur_node is not None:
      if cur_node.val == val:
        return cur_node
      elif cur_node.val > val:
        cur_node = cur_node.left
      else:
        cur_node = cur_node.right

    return False

  def minValueNode(self, node): 
    current = node 
  
    # loop down to find the leftmost leaf 
    while(current.left is not None): 
        current = current.left  
  
    return current

  def delete(self, root, val):
    if root is None: 
      return root
    elif val < root.val:
      root.left = self.delete(root.left, val)
    elif val > root.val:
      root.right = self.delete(root.right, val)
    else:
      # Node with only one child or no child 
      if root.left is None: 
        temp = root.right  
        root = None 
        return temp  

      elif root.right is None: 
          temp = root.left  
          root = None
          return temp 

      # Node with two children: Get the inorder successor 
      # (smallest in the right subtree) 
      temp = self.minValueNode(root.right) 

      # Copy the inorder successor's content to this node 
      root.val = temp.val 

      # Delete the inorder successor 
      root.right = self.delete(root.right, temp.val) 

    return root  

  def print(self):
    self.inorder = []
    self.preorder = []
    self.inorder_dfs(self.root)
    self.preorder_dfs(self.root)

    print(" " + " ".join([ str(i) for i in self.inorder ]))
    print(" " + " ".join([ str(i) for i in self.preorder ]))

  def inorder_dfs(self, root):
    if not root: return

    self.inorder_dfs(root.left)
    self.inorder.append(root.val)
    self.inorder_dfs(root.right)

  def preorder_dfs(self, root):
    if not root: return

    self.preorder.append(root.val)
    self.preorder_dfs(root.left)
    self.preorder_dfs(root.right)


n = int(input())
bst = Bst()
for _ in range(n):
  ins = list(map(str, input().split()))
  order = ins[0]
  if order == "insert":
    val = int(ins[1])
    bst.insert(val)
  elif order == "find":
    val = int(ins[1])
    if not bst.find(val):
      print("no")
    else:
      print("yes")
  elif order == "delete":
    val = int(ins[1])
    bst.delete(bst.root, val)
  elif order == "print":
    bst.print()

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

class Node:
    def __init__(self, id):
        self.id = id
        self.parent = None
        self.left = None
        self.right = None
    
    def __str__(self):
        return 'id={}'.format(self.id)

class BinaryTree:
    def __init__(self):
        self.root = None
        
    def insert(self, node, current_node=None):
        if self.root is None:
            self.root = node
            return
        
        if current_node is None:
            current_node = self.root
            
        if node.id < current_node.id:
            if current_node.left:
                self.insert(node, current_node.left)
            else:
                current_node.left = node
                node.parent = current_node
        else:
            if current_node.right:
                self.insert(node, current_node.right)
            else:
                current_node.right = node
                node.parent = current_node
    
    def delete(self, id, current_node=None):
        if current_node is None:
            current_node = self.root
        
        if id == current_node.id:
            if current_node.left is None and current_node.right is None:
                
                if current_node.parent.left and current_node.parent.left.id == id:
                    current_node.parent.left = None
                else:
                    current_node.parent.right = None
            elif current_node.left and current_node.right:
                result = []
                self.walk_inorder(result, current_node)
                in_id = result[result.index(current_node.id)+1]
                current_node.id = in_id
                self.delete(in_id, current_node.right)
            else:
                child = None
                if current_node.left:
                    child = current_node.left
                else:
                    child = current_node.right
                
                if current_node.parent.left and current_node.parent.left.id == id:
                    child.parent = current_node.parent
                    current_node.parent.left = child
                else:
                    child.parent = current_node.parent
                    current_node.parent.right = child
        elif id < current_node.id:
            if current_node.left:
                self.delete(id, current_node.left)
        elif current_node.id < id:
            if current_node.right:
                self.delete(id, current_node.right)
                
    def walk_inorder(self, result, current_node=None):
        if current_node is None:
            current_node = self.root
        
        if current_node.left:
            self.walk_inorder(result, current_node.left)
            
        result.append(current_node.id)
        
        if current_node.right:
            self.walk_inorder(result, current_node.right)
    
    def walk_preorder(self, result, current_node=None):
        if current_node is None:
            current_node = self.root
        
        result.append(current_node.id)
        
        if current_node.left:
            self.walk_preorder(result, current_node.left)
            
        if current_node.right:
            self.walk_preorder(result, current_node.right)

    def find(self, id, current_node=None):
        if current_node is None:
            current_node = self.root
            
        if current_node.id == id:
            return True
        if id < current_node.id:
            if current_node.left and self.find(id, current_node.left):
                return True
        else:
            if current_node.right and self.find(id, current_node.right):
                return True
        return False

def main():
    n = int(input())
    tree = BinaryTree()
    
    for _ in range(n):
        cmd = input()
        if cmd[0] == 'p':
            result = []
            tree.walk_inorder(result)
            print('', *result)
            
            result = []
            tree.walk_preorder(result)
            print('', *result)
        elif cmd[0] == 'i':
            id = int(cmd.split()[1])
            node = Node(id)
            tree.insert(node)
        elif cmd[0] == 'd':
            id = int(cmd.split()[1])
            tree.delete(id)
        elif cmd[0] == 'f':
            id = int(cmd.split()[1])
            if tree.find(id):
                print('yes')
            else:
                print('no')

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
import sys

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

def insert(key):
    global root
    # The first node
    if root.key is None:
        root.key = key
        return
    # The second note and so forth
    else:
        newNode = Node(key)
        x = root
        while x is not None:
            tmpParent = x # parent 候補として保持
            if newNode.key < x.key:
                x = x.left
            else:
                x = x.right
        newNode.parent = tmpParent
        if newNode.key < tmpParent.key:
            tmpParent.left = newNode
        else:
            tmpParent.right = newNode

def find(key):
    """
    Find a node with the key (x: a node for search)
    :param key: Key to search
    :return: A node that has the key. Returns None if there is no match,
    """
    global root
    x = root
    while x is not None and x.key != key:
        if key < x.key:
            x = x.left
        else:
            x = x.right
    return x

def delete(key):
    global root
    z = find(key)

    if z.left is None or z.right is None:
        nodeToDelete = z
    else:
        nodeToDelete = getSuccessor(z)

    # x = nodeToDelete の子
    if nodeToDelete.left is not None:
        x = nodeToDelete.left
    else:
        x = nodeToDelete.right

    if x is not None:
        x.parent = nodeToDelete.parent

    if nodeToDelete.parent is None:
        root = x
    elif nodeToDelete == nodeToDelete.parent.left:
        nodeToDelete.parent.left = x
    else:
        nodeToDelete.parent.right = x

    if nodeToDelete != z:
        z.key = nodeToDelete.key

    # if x.left is None and x.right is None: # x が子を持たないとき
    #     if x.parent.left == x:
    #         x.parent.left = None
    #     else:
    #         x.parent.right = None
    # elif x.left is None or x.right is None: # x が 1 つだけ子を持つとき
    #     if x.left is not None:
    #         child = x.left
    #     else:
    #         child = x.right
    #     if x.parent.left == x:
    #         x.parent.left = child
    #     else:
    #         x.parent.right = child
    #     child.parent = x.parent
    # else: # x が 2 つ子を持つとき
    #     y = getSuccessor(x)
    #     delete(y.key)
    #     x.key = y.key

def getSuccessor(node):
    """
    node の次節点 (中間巡回で次に来る node を返す
    """
    if node.right is not None:
        return getMinimum(node.right)
    y = node.parent
    while y is not None and node == y.right:
        node = y
        y = y.parent
    return y

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

def inorder(node, result):
    if node is None:
        return
    inorder(node.left, result)
    result.append(node.key)
    inorder(node.right, result)

def preorder(node, result):
    if node is None:
        return
    result.append(node.key)
    preorder(node.left, result)
    preorder(node.right, result)

def printOrderedResult(node, orderFunction):
    """
    :param node: node (root)
    :param orderFunction: inorder or preorder (function)
    :return: nothing
    """
    result = []
    orderFunction(node, result)
    result = [i for i in map(str, result)]
    print(' ', end='')
    print(' '.join(result))


# sys.stdin = open('input.txt')

root = Node()
n = int(input())

for i in range(n):
    command = input()
    try:
        command, key = command.split()
        key = int(key)
        if command == 'insert':
            insert(key)
        elif command == 'find':
            if find(key) is None:
                print('no')
            else:
                print('yes')
        elif command == 'delete':
            delete(key)
    except ValueError: # command == 'print'
        printOrderedResult(root, inorder)
        printOrderedResult(root, preorder)

Submission status: Accepted

Solution code:
import sys

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

root = None

def insert(key):
    global root
    x, y = root, None
    while x: x, y = x.left if key < x.key else x.right, x
    if y is None: root = Node(key)
    elif key < y.key: y.left = Node(key)
    else: y.right = Node(key)

def find(target):
    result = root
    while result and target != result.key:
        result = result.left if target < result.key else result.right
    return result is None

def delete(target):
    def remove_node(p, c, a):
        if p.left == c: p.left = a
        else: p.right = a
    p, c = None, root
    while c.key != target: p, c = c, c.left if target < c.key else c.right
    if c.left is None:
        remove_node(p, c, c.right)
    elif c.right is None:
        remove_node(p, c, c.left)
    elif c.right.left is None:
        c.right.left = c.left
        remove_node(p, c, c.right)
    else:
        g = c.right
        while g.left.left: g = g.left
        c.key = g.left.key
        g.left = g.left.right

def inorder(node):
    return inorder(node.left) + f' {node.key}' + inorder(node.right) if node else ''
def preorder(node):
    return f' {node.key}' + preorder(node.left) + preorder(node.right) if node else ''

input()
for e in sys.stdin:
    if e[0] == 'i': insert(int(e[7:]))
    elif e[0] == 'd': delete(int(e[7:]))
    elif e[0] == 'f': print(['yes','no'][find(int(e[5:]))])
    else: print(inorder(root)); print(preorder(root))

Submission status: Accepted

Solution code:
n = int(input())
COM = [list(input().split()) for _ in range(n)]

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

    def inorder(self,List):
        if self.data != None:
            if self.left != None:
                self.left.inorder(List)
            List.append(self.data)
            if self.right != None:
                self.right.inorder(List)
        return List

    def preorder(self,List):
        if self.data != None:
            List.append(self.data)
            if self.left != None:
                self.left.preorder(List)
            if self.right != None:
                self.right.preorder(List)
        return List

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

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

    def find(self,data,sw):
        pt = self.root
        flag = 0
        while pt != None:
            if pt.data == data:
                flag = 1
                if sw == 1:
                    print("yes")
                return 1
            elif pt.data > data:
                pt = pt.left
            else:
                pt = pt.right
        if flag == 0:
            if sw == 1:
                print("no")
            return 0

    def delete(self,data):
        if self.find(data,0) == 1:
            pt = self.root
            while pt != None:
                if pt.data == data:
                    break
                elif pt.data > data:
                    pt = pt.left
                else:
                    pt = pt.right
            if pt.left == None and pt.right == None: #子0個
                if pt.data < pt.parent.data:
                    pt.parent.left , pt = None , None
                else:
                    pt.parent.right , pt = None , None
            elif pt.left != None and pt.right == None: #子1個
                if pt.data < pt.parent.data:
                    pt.parent.left , pt.left.parent , pt = pt.left , pt.parent , None
                else:
                    pt.parent.right , pt.left.parent , pt = pt.left , pt.parent , None
            elif pt.left == None and pt.right != None: #子1個
                if pt.data < pt.parent.data:
                    pt.parent.left , pt.right.parent , pt = pt.right , pt.parent , None
                else:
                    pt.parent.right , pt.right.parent , pt = pt.right , pt.parent , None
            else: #子2個
                y = self.getSuccessor(pt) #ptを根とする右部分木のnode.dataの最小値
                pt.data = y.data
                if y.right == None:
                    if y.data < y.parent.data:
                        y.parent.left , y = None , None
                    else:
                        y.parent.right , y = None , None
                else:
                    if y.data < y.parent.data:
                        y.parent.left , y.right.parent , y = y.right , y.parent , None
                    else:
                        y.parent.right , y.right.parent , y = y.right , y.parent , None
    def getSuccessor(self,x): #次節点
        if x.right != None:
            return self.getMinimum(x.right)
        y = x.parent
        while y != None and x == y.right:
            x = y
            y = y.parent
        return y

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

    def print(self):
        print(""," ".join(map(str,self.root.inorder([])))) #なぜかjoinを使ったら速くなった
        print(""," ".join(map(str,self.root.preorder([]))))

btree = BTree()
cnt = 0
for i in range(n):
    if COM[i][0] == "insert":
        node = Node(int(COM[i][1]))
        btree.insert(node)
        cnt += 1
    elif COM[i][0] == "find":
        btree.find(int(COM[i][1]),1)
    elif COM[i][0] == "delete":
        btree.delete(int(COM[i][1]))
    else:
        btree.print()

Submission status: Accepted

Solution code:
# 二分探索　データの削除から　クラス定義を用いて
class Node:
    def __init__(self, key):
        self.key = key
        self.parent = None
        self.left = None
        self.right = None

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

    def insert(self, key):
        root_node = self.root
        insert_node = Node(key)
        parent_node = None

        while root_node:
            parent_node = root_node
            if insert_node.key < root_node.key:
                root_node = root_node.left
            else:
                root_node = root_node.right
            
        insert_node.parent = parent_node

        if parent_node == None:
            self.root = insert_node
        elif insert_node.key < parent_node.key:
            parent_node.left = insert_node
        else:
            parent_node.right = insert_node
        
    def find(self, key):
        node = self.root

        while node:
            if node.key == key:
                return node
            elif node.key < key:
                node = node.right
            else:
                node = node.left 

        return None

    def delete(self, key):
        node = self.find(key)

        if node == None:
            return 
        
        if node.left and node.right:
            next_node = node.right

            while next_node.left:
                next_node = next_node.left

            node.key = next_node.key
            node = next_node

        if node.left:
            node.left.parent = node.parent
            if node.parent.left == node:
                node.parent.left = node.left
            else:
                node.parent.right = node.left
        elif node.right:
            node.right.parent = node.parent
            if node.parent.left == node:
                node.parent.left = node.right
            else:
                node.parent.right = node.right
        else:
            if node.parent.left == node:
                node.parent.left = None
            else:
                node.parent.right = None

    def show_inorder(self, node):
        if node == None:
            return 
        self.show_inorder(node.left)
        print(' ' + str(node.key), end = '')
        self.show_inorder(node.right)

    def show_preorder(self, node):
        if node == None:
            return 
        print(' ' + str(node.key), end = '')
        self.show_preorder(node.left)
        self.show_preorder(node.right)

tree = BinarySearchTree()
n = int(input())

for i in range(n):
    command = input().split()

    if command[0] == 'insert':
        tree.insert(int(command[1]))
    elif command[0] == 'find':
        a = tree.find(int(command[1]))
        if a != None:
            print('yes')
        else:
            print('no')        
    elif command[0] == 'delete':
        tree.delete(int(command[1]))
    elif command[0] == 'print':
        tree.show_inorder(tree.root)
        print()
        tree.show_preorder(tree.root)
        print()

Submission status: Accepted

Solution code:
if __name__ == '__main__':
    import sys
    input = sys.stdin.readline

    NIL = -1

    m = int(input())

    root = NIL

    def insert(k):
        global root
        y = NIL
        x = root
        z = {'key':k, 'left':NIL, 'right':NIL}
        while x != NIL:
            y = x
            if z['key'] < x['key']:
                x = x['left']
            else:
                x = x['right']
        z['parent'] = y

        if y == NIL:
            root = z
        elif z['key'] < y['key']:
            y['left'] = z
        else:
            y['right'] = z

    def find(u, k):
        while u != NIL and k != u['key']:
            if k < u['key']:
                u = u['left']
            else:
                u = u['right']
        return u

    def tree_minimum(x):
        while x['left'] != NIL:
            x = x['left']
        return x

    def tree_successor(x):
        if x['right'] != NIL:
            return tree_minimum(x['right'])
        y = x['parent']
        while y != NIL and x == y['right']:
            x = y
            y = y['parent']
        return y

    def tree_delete(z):
        global root
        if z['left'] == NIL or z['right'] == NIL:
            y = z
        else:
            y = tree_successor(z)
        # yの子xを決める
        if y['left'] != NIL:
            x = y['left']
        else:
            x = y['right']

        if x != NIL:
            x['parent'] = y['parent']

        if y['parent'] == NIL:
            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(u):
        if u == NIL:
            return
        inorder(u['left'])
        print(' ' + str(u['key']), end='')
        inorder(u['right'])

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

    for _ in range(m):
        command = input()
        if command[0] == 'f':
            _, x = command.split()
            x = int(x)
            t = find(root, x)
            if t != NIL:
                print('yes')
            else:
                print('no')
        elif command[:6] == 'insert':
            _, x = command.split()
            x = int(x)
            insert(x)
        elif command[:5] == 'print':
            inorder(root)
            print('')
            # pythonのprintは最後に改行記号をつけてくれるので、これで改行できる
            preorder(root)
            print('')
        else:
            _, x = command.split()
            x = int(x)
            tree_delete(find(root, x))

Submission status: Accepted

Solution code:
class Tree:
    root = None

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

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

    def print(self):
        print(' ', end='')
        print(*self.root.print_in())
        print(' ', end='')
        print(*self.root.print_pre())

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

    def delete1(self, node):
        y = node.parent
        if y.key < node.key:
          y.right = None
        elif y.key > node.key:
          y.left = None
        node.parent = None

    def delete2(self, node):
        y = node.parent
        if y.key < node.key:
          y.right = node.right
        else:
          y.left = node.right
        node.right.parent = y

    def delete3(self, node):
        y = node.parent
        if y.key < node.key:
          y.right = node.left
        else:
          y.left = node.left
        node.left.parent = y
    
    def delete4(self, node):
        y = node.right
        x = y
        while x.left:
          x = x.left

        node.key = x.key
        if y == x:
          node.right = None
          
        if not x.left and not x.right:
          self.delete1(x)
        elif not x.left and x.right:
          self.delete2(x)
        else:
          self.delete3(x)

    def delete(self, node):
        y = self.find(node)
        if y:
          if not y.left and not y.right:
             self.delete1(y)

          elif not y.left and y.right:
             self.delete2(y)
        
          elif y.left and not y.right:
             self.delete3(y)

          else:
             self.delete4(y)

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

    def print_pre(self):
        yield self.key
        if self.left:
            for k in self.left.print_pre(): yield k
        if self.right:
            for k in self.right.print_pre(): yield k

    def print_in(self):
        if self.left:
            for k in self.left.print_in(): yield k
        yield self.key
        if self.right:
            for k in self.right.print_in(): yield k


tree = Tree()
m = int(input())

while m:
    l = input().split()
    if len(l) == 2 and l[0] == "insert":
       tree.insert(Node(int(l[1])))
    elif len(l) == 2 and l[0] == "find":
       y = tree.find(Node(int(l[1])))
       if y:
          print("yes")
    elif len(l) == 2 and l[0] == "delete":
       tree.delete(Node(int(l[1])))
    else:
       tree.print()
    m -= 1