从二叉搜索树(python)中删除?

时间:2017-07-02 03:08:42

标签: python python-3.x binary-search-tree

我正在尝试从二叉搜索树插入和删除。到目前为止,我的插入功能有效,但我的删除功能不是。我正在查看我的代码,但在其中找不到任何明显的错误。我收到的错误消息是line 69: root.right_child = self._recurisve_delete(root.right_child, value) AttributeError: 'Binary_Search_Tree' object has no attribute '_recurisve_delete'"这里实际发生了什么?

def _recursive_delete(self, root, value):
  if self.root is None:
      raise ValueError("Tree is Empty") 
  if root.value == value:
     successor = None
     if root.right_child and root.left_child:
         successor, parent = root.right_child, root
         while successor.left_child:
             successor, parent = successor.left_child, successor
         if parent.left_child == successor:
             parent.left_child = successor.right_child
         else:
             parent.right_child = successor.right_child
         successor.left_child = root.left_child
         successor.right_child = root.right_child
         self._update_heights(successor, root.height)
         return successor
     if root.left_child:
       self._update_heights(root.left_child, root.height)
       return root.left_child
     elif root.right_child:
       self._update_heights(root.right_child, root.height)
       return root.right_child
     self._update_heights(root, root.height)
     return
  if root.value > value and root.left_child is not None:
      root.left_child = self._recursive_delete(root.left_child, value)
  elif root.value < value and root.right_child is not None:
      root.right_child = self._recurisve_delete(root.right_child, value)
  return root

def remove_element(self, value):
  self._recursive_delete(self.root, value)
  self.height -= 1
  return self.root

以下是我使用的测试代码:

if __name__ == '__main__':
  bst = Binary_Search_Tree()
  values = [7, 2, 22, 5, 1, 8, 3, 6, 9, 8, 4, 11, 10, 12]
  print('insert values', values)
  for val in values:
      bst.insert_element(val) #this all works well#
  print('in-order: ', bst.in_order(), '\n')
  bst.remove_element(22)

输出:

in-order:  [1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 11, 12, 22] 

当我尝试删除元素时出现错误。任何见解都将不胜感激!

1 个答案:

答案 0 :(得分:0)

这只是一个错字。

elif root.value < value and root.right_child is not None:
      root.right_child = self._recurisve_delete(root.right_child, value)

应该是

elif root.value < value and root.right_child is not None:
      root.right_child = self._recursive_delete(root.right_child, value)