Advertisement
Guest User

Untitled

a guest
Oct 26th, 2017
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. class ListBinaryTree:
  2. """A binary tree class with nodes as lists."""
  3. DATA = 0 # just some constants for readability
  4. LEFT = 1
  5. RIGHT = 2
  6.  
  7. def __init__(self, root_value, left=None, right=None):
  8. """Create a binary tree with a given root value
  9. left, right the left, right subtrees
  10. """
  11. self.node = [root_value, left, right]
  12.  
  13. def create_tree(self, a_list):
  14. return ListBinaryTree(a_list[0], a_list[1], a_list[2])
  15.  
  16. def insert_left(self, value):
  17. """Inserts value to the left of this node.
  18. Pushes any existing left subtree down as the left child of the new node.
  19. """
  20. self.node[self.LEFT] = ListBinaryTree(value, self.node[self.LEFT], None)
  21.  
  22. def insert_right(self, value):
  23. """Inserts value to the right of this node.
  24. Pushes any existing left subtree down as the left child of the new node.
  25. """
  26. self.node[self.RIGHT] = ListBinaryTree(value, None, self.node[self.RIGHT])
  27.  
  28. def insert_tree_left(self, tree):
  29. """Inserts new left subtree of current node"""
  30. self.node[self.LEFT] = tree
  31.  
  32. def insert_tree_right(self, tree):
  33. """Inserts new left subtree of current node"""
  34. self.node[self.RIGHT] = tree
  35.  
  36. def set_value(self, new_value):
  37. """Sets the value of the node."""
  38. self.node[self.DATA] = new_value
  39.  
  40. def get_value(self):
  41. """Gets the value of the node."""
  42. return self.node[self.DATA]
  43.  
  44. def get_left_subtree(self):
  45. """Gets the left subtree of the node."""
  46. return self.node[self.LEFT]
  47.  
  48. def get_right_subtree(self):
  49. """Gets the right subtree of the node."""
  50. return self.node[self.RIGHT]
  51.  
  52. def __str__(self):
  53. return '['+str(self.node[self.DATA])+', '+str(self.node[self.LEFT])+', '+\
  54. str(self.node[self.RIGHT])+']'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement