简体   繁体   中英

Deleting from binary search tree (python)?

I'm trying to insert and delete from a binary search tree. So far my insert function works, but my removal one isn't. I'm looking through my code and can't find any obvious errors in it. The error message I'm getting is line 69: root.right_child = self._recurisve_delete(root.right_child, value) AttributeError: 'Binary_Search_Tree' object has no attribute '_recurisve_delete'" What is actually happening here?

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

Here is the test code I used:

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)

Output:

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

The error comes when I try to remove the elements. Any insight would be appreciated!

It's only a typo.

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

should be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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