Advertisement
Guest User

Untitled

a guest
Sep 27th, 2016
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. """A module for practicing with Binary Search Trees"""
  2.  
  3. class BST:
  4. """A simple binary search tree with no self-balancing"""
  5.  
  6. # Constructors for tree nodes and a two-element tree
  7. class Node:
  8. __slots__ = "_value", "_left", "_right"
  9. def __init__(self, l, v, r):
  10. self._left = l;
  11. self._value = v;
  12. self._right = r
  13. def __init__(self):
  14. """This initializes the tree to contain 2 values
  15. so the minimum function has something to work with"""
  16. self._root = self.Node(None, 4, self.Node(None, 6, None))
  17.  
  18. # Some methods taht will not need any change during recitation
  19. def _rec_tuples(self, here):
  20. """Recursively convert tree into a tuple form"""
  21. if here is None:
  22. return ''
  23. else:
  24. return (self._rec_tuples(here._left),
  25. here._value, self._rec_tuples(here._right))
  26. def __str__(self):
  27. """Return a cleaned-up tuple version of the entire tree"""
  28. tuples = self._rec_tuples(self._root)
  29. return str(tuples).replace("'', ","").replace(", ''","")
  30.  
  31. def max(self):
  32. """Return maximum value stored in binary search tree"""
  33. return self._rec_max(self._root)
  34. def insert(self, value):
  35. """Insert a single occurrence of given value into the tree"""
  36. self._root = self._rec_insert(self._root, value)
  37. def remove(self, value):
  38. """Remove a single occurrence of given value from the tree"""
  39. self._root = self._rec_remove(self._root, value)
  40.  
  41. # And three methods to work on during recitation
  42. def _rec_max(self, here):
  43. """Recursively seek the largest value in the tree"""
  44. return NotImplemented
  45.  
  46. def _rec_insert(self, here, value):
  47. """Recursively insert a value, returning a new tree"""
  48. if here is None:
  49. return self.Node(value, None, None)
  50. else:
  51. return here
  52.  
  53. def _rec_remove(self, here, value):
  54. """Recursively remove a value once, returning a new value"""
  55. if here is None:
  56. return None
  57. else:
  58. return here
  59.  
  60. # Create a Tree and insert several values
  61. T = BST()
  62. print("Maximum value is", T.max())
  63.  
  64. inserts = [1,5,2,3,7,0,0,4]
  65. print("Insert ",inserts)
  66. for v in inserts:
  67. T.insert(v)
  68. print(T)
  69. print("Maximum value is", T.max())
  70.  
  71. removes = [0,5,6,2,4]
  72. print("Remove ",removes)
  73. for v in removes:
  74. T.remove(v)
  75. print(T)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement