Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. class Node:
  2. def __init__(self, value=None):
  3. # 記得class的特性, 每一個Node, 皆要去實現這4個 屬性的components.
  4. self.value = value
  5. self.left = None
  6. self.right = None
  7. self.parent = None
  8.  
  9. def __repr__(self):
  10. # Helpful method to keep track of Node values.
  11. return "<Node: {}>".format(self.value)
  12.  
  13. class MaxHeap:
  14. def __init__(self):
  15. self.root = None
  16.  
  17. # Implement your `insert` method here.
  18.  
  19. def insert(self, value):
  20. # create a node for when calling the insert method
  21. node = Node(value=value)
  22. # if root of the MaxHeap tree is not existed, set the firstly insert node as root.
  23. # case 1: the root is not existed, have to set the new insert node to the root.
  24. if not self.root:
  25. self.root = node
  26. return node
  27. # if the root existed, compare the value of the root node with the inserted node.
  28. # case 2: the root existed, and the root value >= inserted value ======> is the normal insert.
  29. if self.root.value >= node.value:
  30. # Normal insert.
  31. node.parent = self.root
  32. if not self.root.left:
  33. self.root.left = node
  34. elif not self.root.right:
  35. self.root.right = node
  36. # remember for each
  37. return node
  38.  
  39.  
  40. # case 3: the root existed, and the root value < inserted value =======> is the swap insert.
  41. # Swap the nodes.
  42.  
  43. old_root = self.root
  44. node.left = old_root.left
  45. node.right = old_root.right
  46. self.root = node
  47.  
  48. if not self.root.left:
  49. self.root.left = old_root
  50. elif not self.root.right:
  51. self.root.right = old_root
  52. return node
  53.  
  54. if __name__=="__main__":
  55. heap = MaxHeap()
  56. heap.insert(3)
  57. heap.insert(9)
  58. heap.insert(11)
  59. root = heap.root.value
  60. left = heap.root.left.value
  61. right = heap.root.right.value
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement