繁体   English   中英

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

[英]Deleting from binary search tree (python)?

我正在尝试从二叉搜索树中插入和删除。 到目前为止,我的插入功能有效,但我的删除功能无效。 我正在查看我的代码,但找不到任何明显的错误。 我收到的错误消息是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] 

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

这只是一个错字。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM