Advertisement
Guest User

Untitled

a guest
Aug 24th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. class Node:
  2. def __init__(self, left=None, right=None):
  3. self.left = left
  4. self.right = right
  5.  
  6. def count(self):
  7. # count this node
  8. total = 1
  9.  
  10. # if left child exists, get its count
  11. if self.left is not None:
  12. total += self.left.count()
  13.  
  14. # if right child exists, add its count
  15. total += self.right.count()
  16.  
  17. return total
  18.  
  19. # Hack to let us put nodes in a set
  20. __hash__ = object.__hash__
  21.  
  22. # Empty node
  23. n = Node()
  24. assert n.count() == 1
  25.  
  26. # Two children
  27. a = Node()
  28. b = Node()
  29. root = Node(a, b)
  30. assert root.count() == 3
  31.  
  32. # root.right.right is root
  33. root = Node() # root
  34. a = Node() # / \
  35. b = Node() # a b
  36. c = Node() # / \
  37. # c root
  38. root.left = a
  39. root.right = b
  40. b.left = c
  41. b.right = root
  42.  
  43. # Max recursion depth
  44. root.count()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement