Problem:
Binary Search Tree III Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II.  insert $k$: Insert a node containing $k$ as key into $T$.  find $k$: Report whether $T$ has a node containing $k$.  delete $k$: Delete a node containing $k$.  print : Print the keys of the binary search tree by inorder tree walk and  preorder tree walk respectively.  The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases:  If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$).  If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent.  If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key.  Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print " yes " if $T$ has a node containing $k$, " no " if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key  Constraints   The number of operations $\leq 500,000$  The number of print operations $\leq 10$.  $-2,000,000,000 \leq key \leq 2,000,000,000$  The height of the binary tree does not exceed 100 if you employ the above pseudo code.  The keys in the binary search tree are all different.   Sample Input 1  18
insert 8
insert 2
insert 3
insert 7
insert 22
insert 1
find 1
find 2
find 3
find 4
find 5
find 6
find 7
find 8
print
delete 3
delete 7
print  Sample Output 1  yes
yes
yes
no
no
no
yes
yes
 1 2 3 7 8 22
 8 2 1 3 7 22
 1 2 8 22
 8 2 1 22  Reference  Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

Solution (Python):

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

Solution (Python):


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)

Solution (Python):
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:
                
                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
                    
                if act != "":
                    setattr(temp, act, new_leaf)
                    
                    if new_leaf is not None:
                        new_node = getattr(temp, act)
                        setattr(new_node, "parent", temp)
                        
                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)
                    
                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))

Solution (Python):
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:
                
                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
                    
                if act != "":
                    setattr(temp, act, new_leaf)
                    
                    if new_leaf is not None:
                        new_node = getattr(temp, act)
                        setattr(new_node, "parent", temp)
                        
                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)
                    
                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))

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

class BST:
  root = None
  def insert(self, key):
    x = self.root
    y = None
    z = Node(key)
    while x != None:
      y = x
      if(z.key < y.key):
        x = x.left
      elif(y.key < z.key):
        x = x.right
    
    if y is None:
      
      self.root = z
    else:
      
      if z.key < y.key:
        y.left = z
      elif y.key < z.key:
        y.right = z
        
  def preorder(self, par):
    if par is not None:
      print(" {}".format(par.key), end="")
      self.preorder(par.left)
      self.preorder(par.right)
  
  def inorder(self, par):
    if par is not None:
      self.inorder(par.left)
      print(" {}".format(par.key), end="")
      self.inorder(par.right)
      
  def find(self, key):
    x = self.root
    y = None
    z = Node(key)
    flag = False
    while x is not None: 
      y = x
      if(z.key < y.key):
        x = x.left
      elif(y.key < z.key):
        x = x.right
      else:
        flag = True
        break
    return flag
  
  def delete(self, key):
    if self.find(key):
      x = self.root
      y = None

      while x is not None: 
        y = x
        if(key < y.key):
          x = x.left
        elif(y.key < key):
          x = x.right
        else:
          
          break
        if(x.key == key):
          break

      
      x_children  = [c for c in [x.left, x.right] if c is not None]
      if len(x_children) == 0:
        
        for c in [y.left, y.right]:
          if c is not None and c.key == key:
            
            which_side = [i for i, x in enumerate([y.left, y.right]) if x is not None and x.key == c.key][0]
            if which_side == 0:
              
              y.left = None
            else:
              
              y.right = None
      elif len(x_children) == 1:
        
        for c in [y.left, y.right]:
          if c is not None and c.key == key:
            
            which_side = [i for i, x in enumerate([y.left, y.right]) if x is not None and x.key == c.key][0]
            if which_side == 0:
              
              y.left = x_children[0]
            else:
              
              y.right = x_children[0]
      else:
        
        
        
        
        min_child = x.right
        
        par = x
        while True:
          if min_child.left is None:
            break
          par = min_child
          min_child = min_child.left

        
        if(par.key == key):
          
          pass
        else:
          par.left = None
          min_child.right = x.right
          
        
        x_side = [i for i, s in enumerate([y.left, y.right]) if s is not None and s.key == x.key][0]
        
        if x_side == 0:
          
          y.left = min_child
        else:
          
          y.right = min_child
          
        min_child.left = x.left
        
      
n = int(input())
bst = BST()
for _ in range(n):
  query = input().split()
  if query[0] == "insert":
    bst.insert(int(query[1]))
  elif query[0] == "find":
    print("yes" if bst.find(int(query[1])) else "no")
  elif query[0] == "print":
    
    root = bst.root
    bst.inorder(root)
    print()
    bst.preorder(root)
    print()
  elif query[0] == "delete":
    bst.delete(int(query[1]))

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

class BST:
  root = None
  def insert(self, key):
    x = self.root
    y = None
    z = Node(key)
    while x != None:
      y = x
      if(z.key < y.key):
        x = x.left
      elif(y.key < z.key):
        x = x.right
    
    if y is None:
      
      self.root = z
    else:
      
      if z.key < y.key:
        y.left = z
      elif y.key < z.key:
        y.right = z
        
  def preorder(self, par):
    if par is not None:
      print(" {}".format(par.key), end="")
      self.preorder(par.left)
      self.preorder(par.right)
  
  def inorder(self, par):
    if par is not None:
      self.inorder(par.left)
      print(" {}".format(par.key), end="")
      self.inorder(par.right)
      
  def find(self, key):
    x = self.root
    y = None
    z = Node(key)
    flag = False
    while x is not None: 
      y = x
      if(z.key < y.key):
        x = x.left
      elif(y.key < z.key):
        x = x.right
      else:
        flag = True
        break
    return flag
  
  def delete(self, key):
    if self.find(key):
      x = self.root
      y = None

      while x is not None: 
        y = x
        if(key < y.key):
          x = x.left
        elif(y.key < key):
          x = x.right
        else:
          
          break
        if(x.key == key):
          break

      
      x_children  = [c for c in [x.left, x.right] if c is not None]
      if len(x_children) == 0:
        
        for c in [y.left, y.right]:
          if c is not None and c.key == key:
            
            which_side = [i for i, x in enumerate([y.left, y.right]) if x is not None and x.key == c.key][0]
            if which_side == 0:
              
              y.left = None
            else:
              
              y.right = None
      elif len(x_children) == 1:
        
        for c in [y.left, y.right]:
          if c is not None and c.key == key:
            
            which_side = [i for i, x in enumerate([y.left, y.right]) if x is not None and x.key == c.key][0]
            if which_side == 0:
              
              y.left = x_children[0]
            else:
              
              y.right = x_children[0]
      else:
        
        
        min_child = x.right
        
        par = x
        while True:
          if min_child.left is None:
            break
          par = min_child
          min_child = min_child.left

        if(par.key == key):
          
          pass
        else:
          
          par.left = None
          min_child.right = x.right
          
        
        x_side = [i for i, s in enumerate([y.left, y.right]) if s is not None and s.key == x.key][0]
        
        if x_side == 0:
          
          y.left = min_child
        else:
          
          y.right = min_child
        
        min_child.left = x.left
      
n = int(input())
bst = BST()
for _ in range(n):
  query = input().split()
  if query[0] == "insert":
    bst.insert(int(query[1]))
  elif query[0] == "find":
    print("yes" if bst.find(int(query[1])) else "no")
  elif query[0] == "print":
    
    root = bst.root
    bst.inorder(root)
    print()
    bst.preorder(root)
    print()
  elif query[0] == "delete":
    bst.delete(int(query[1]))

Solution (Python):
class Node:
    def __init__(self, key):
        self.key = key
        self.parent = None
        self.left = None
        self.right = None
class Tree:
    def __init__(self):
        self.root = None
        self.inorder = []
        self.preorder = []

    def insert(self, node):

        p = None
        x = self.root        
        while x is not None:
            p = x
            
            if node.key <= x.key:
                x = x.left
            else:
                x = x.right

        
        node.parent = p

        if p is None:
            self.root = node
        else:
            
            if node.key <= p.key:
                
                p.left = node
            else:
                
                p.right = node

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

    def delete(self, z):
        
        
        
        p = z.parent
        

        
        if z.left is None and z.right is None:
            
            if p.left == z:
                p.left = None
            else:
                p.right = None

        
        elif z.left is not None and z.right is not None:
            
            next_node = tree.get_next_node(z)
            
            z.key = next_node.key
            self.delete(next_node)

        
        else:
            
            
            if p.left == z:
                if z.left is not None:
                    p.left = z.left
                    z.left.parent = p
                else:
                    p.left = z.right
                    z.right.parent = p
            else:
                
                if z.left is not None:
                    p.right = z.left
                    z.left.parent = p
                else:
                    p.right = z.right
                    z.right.parent = p

    def get_next_node(self, node):
        if node.right is not None:
            
            return self.get_minimum(node.right)
        p = x.parent
        while p is not None and p != p.parent.left:
            p = p.parent
        return p.parent

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

    def print_inorder(self):
        self.inorder = []
        self.inorder_traverse(self.root)
        print(' ' + ' '.join(map(str, self.inorder)))

    def print_preorder(self):
        self.preorder = []
        self.preorder_traverse(self.root)
        print(' ' + ' '.join(map(str, self.preorder)))

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

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

tree = Tree()
m = int(input())
for i in range(m):
    line = input().split()
    if line[0] == 'print':
        
        tree.print_inorder()
        tree.print_preorder()
        
        
        
        
        
    elif line[0] == 'insert':
        key = int(line[1])
        tree.insert(Node(key))
    elif line[0] == 'find':
        key = int(line[1])
        if tree.find(key):
            print('yes')
        else:
            print('no')
    elif line[0] == 'delete':
        
        
        
        
        
        
        
        key = int(line[1])
        
        node = tree.find(key)
        
        tree.delete(node)