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: Wrong Answer

Solution code:
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 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
                if root.left is None:
                    new_leaf = root.right
                elif root.right is None:
                    new_leaf = root.left
                else:
                    new_leaf = root.left
                    rest = root.right
                if act != "":
                    setattr(temp, act, new_leaf)
                else:
                    self.root = new_leaf
                if rest is not None:
                    temp = getattr(temp, act)
                    setattr(temp, act, rest)
                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: Wrong Answer

Solution code:
import sys
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 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
                if root.left is None:
                    new_leaf = root.right
                elif root.right is None:
                    new_leaf = root.left
                else:
                    new_leaf = root.left
                    rest = root.right
                if act != "":
                    setattr(temp, act, new_leaf)
                else:
                    self.root = new_leaf
                if rest is not None:
                    temp = getattr(temp, act)
                    setattr(temp, "right", rest)
                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: Wrong Answer

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 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
                if root.left is None:
                    new_leaf = root.right
                elif root.right is None:
                    new_leaf = root.left
                else:
                    new_leaf = root.right
                    rest = root.left
                if act != "":
                    setattr(temp, act, new_leaf)
                else:
                    self.root = new_leaf
                if rest is not None:
                    temp = getattr(temp, act)
                    setattr(temp, "right", rest)
                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: Wrong Answer

Solution code:
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:
      # yがターゲットになっているので
      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:
          # rootが対象のノードの場合
          break
        if(x.key == key):
          break

      # yが親、子のxがdeleteの対象
      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:
            # yの左右どっちにcがあるのか同定してx_children[0]をぶちこむ
            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:
            # yの左右どっちにcがあるのか同定してx_children[0]をぶちこむ
            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:
        # 削除予定の子から左側のうち最大のものをとってきて、削除予定のやつを削除したのちそこに入れる
        max_child = x.left
        # 一つ上の親を保持
        par = x
        while True:
          if max_child.right is None:
            break
          par = max_child
          max_child = max_child.right
        
        x.key = max_child.key
        par.right = max_child.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]))

Submission status: Wrong Answer

Solution code:
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:
      # yがターゲットになっているので
      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:
          # rootが対象のノードの場合
          break
        if(x.key == key):
          break

      # yが親、子のxがdeleteの対象
      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:
            # yの左右どっちにcがあるのか同定してx_children[0]をぶちこむ
            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:
            # yの左右どっちにcがあるのか同定してx_children[0]をぶちこむ
            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:
        # print("ふたこぶ")
        # print("key: {}".format(key))
        # 削除予定の子から左側のうち最大のものをとってきて、削除予定のやつを削除したのちそこに入れる
        max_child = x.left
        # 一つ上の親を保持
        par = x
        while True:
          if max_child.right is None:
            break
          max_child = max_child.right
        # 大本の削除対象のxの親であるyの左右どちらがxであるか同定し更新
        x_side = [i for i, s in enumerate([y.left, y.right]) if s is not None and s.key == x.key][0]
        # それを直接max_childとする
        if x_side == 0:
          # 左
          y.left = max_child
        else:
          # 右
          y.right = max_child
          
        max_child.right = x.right
        # print("---------------------------")
      
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]))

Submission status: Wrong Answer

Solution code:
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
            # print(node.key, x.key)
            if node.key <= x.key:
                x = x.left
            else:
                x = x.right

        # insertするnodeの親を設定
        node.parent = p

        if p is None:
            self.root = node
        else:
            # insertするnodeを親のleftかrightに設定
            if node.key <= p.key:
                # print('leftに設定')
                p.left = node
            else:
                # print('rightに設定')
                p.right = node

    def find(self, key):
        # print('find: ', str(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):
        print("delete =========")
        print(z.key)
        print(z.parent)
        p = z.parent

        # 1. zが子を持たない場合
        if z.left is None and z.right is None:
            print('pattern 1')
            if p.left.key == z.key:
                p.left = None
            else:
                p.right = None

        # 3. zが子を2つ持つ場合
        elif z.left is not None and z.right is not None:
            print('pattern 2')
            next_node = tree.get_next_node(z)
            z.key = next_node.key
            if next_node == next_node.parent.left:
                next_node.parent.left = None
            else:
                next_node.parent.right = None

        # 2. zがちょうど1つの子を持つ場合
        else:
            print('pattern 3')
            # zが左子だった場合
            if p.left.key == z.key:
                if z.left is not None:
                    p.left = z.left
                    z.left.parent = p
                else:
                    p.left = z.right
                    z.right.parent = p
            else:
                # zが右子だった場合
                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)
        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':
        # print("current tree----")
        # print(tree.root.key)
        # print(tree.root.left.key)
        # print(tree.root.left.right.key)
        # print(tree.root.left.right.parent.key)
        # print("current tree----")
        key = int(line[1])
        node = tree.find(key)
        # print(node.key)
        tree.delete(node)

Submission status: Wrong Answer

Solution code:
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
            # print(node.key, x.key)
            if node.key <= x.key:
                x = x.left
            else:
                x = x.right

        # insertするnodeの親を設定
        node.parent = p

        if p is None:
            self.root = node
        else:
            # insertするnodeを親のleftかrightに設定
            if node.key <= p.key:
                # print('leftに設定')
                p.left = node
            else:
                # print('rightに設定')
                p.right = node

    def find(self, key):
        # print('find: ', str(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):
        # print("delete =========", z.key)
        # print(z.key)
        # print(z.parent)
        p = z.parent
        print(p.key)

        # 1. zが子を持たない場合
        if z.left is None and z.right is None:
            # print('pattern 1')
            if p.left == z:
                p.left = None
            else:
                p.right = None

        # 3. zが子を2つ持つ場合
        elif z.left is not None and z.right is not None:
            # print('pattern 2')
            next_node = tree.get_next_node(z)
            z.key = next_node.key
            self.delete(next_node)

        # 2. zがちょうど1つの子を持つ場合
        else:
            # print('pattern 3')
            # zが左子だった場合
            if p.left.key == z.key:
                if z.left is not None:
                    p.left = z.left
                    z.left.parent = p
                else:
                    p.left = z.right
                    z.right.parent = p
            else:
                # zが右子だった場合
                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)
        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':
        # print('root', str(tree.root.key))
        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':
        
        # print("current tree----")
        # print(tree.root.key)
        # print(tree.root.left.key)
        # print(tree.root.left.right.key)
        # print(tree.root.left.right.parent.key)
        # print("current tree----")
        key = int(line[1])
        # print('delete', str(key))
        node = tree.find(key)
        # print('node.key', node.key)
        tree.delete(node)