Guest User

Untitled

a guest
Jul 2nd, 2014
395
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. def find_min(self): # Gets minimum node (leftmost leaf) in a subtree
  2. current_node = self
  3. while current_node.left_child:
  4. current_node = current_node.left_child
  5. return current_node
  6.  
  7. def replace_node_in_parent(self, new_value=None):
  8. if self.parent:
  9. if self == self.parent.left_child:
  10. self.parent.left_child = new_value
  11. else:
  12. self.parent.right_child = new_value
  13. if new_value:
  14. new_value.parent = self.parent
  15.  
  16. def binary_tree_delete(self, key):
  17. if key < self.key:
  18. self.left_child.binary_tree_delete(key)
  19. elif key > self.key:
  20. self.right_child.binary_tree_delete(key)
  21. else: # delete the key here
  22. if self.left_child and self.right_child: # if both children are present
  23. successor = self.right_child.find_min()
  24. self.key = successor.key
  25. successor.binary_tree_delete(successor.key)
  26. elif self.left_child: # if the node has only a *left* child
  27. self.replace_node_in_parent(self.left_child)
  28. elif self.right_child: # if the node has only a *right* child
  29. self.replace_node_in_parent(self.right_child)
  30. else: # this node has no children
  31. self.replace_node_in_parent(None)
Advertisement
Add Comment
Please, Sign In to add comment