Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node:
- def __init__(self, left=None, right=None):
- self.left = left
- self.right = right
- def count(self):
- # count this node
- total = 1
- # if left child exists, get its count
- if self.left is not None:
- total += self.left.count()
- # if right child exists, add its count
- total += self.right.count()
- return total
- # Hack to let us put nodes in a set
- __hash__ = object.__hash__
- # Empty node
- n = Node()
- assert n.count() == 1
- # Two children
- a = Node()
- b = Node()
- root = Node(a, b)
- assert root.count() == 3
- # root.right.right is root
- root = Node() # root
- a = Node() # / \
- b = Node() # a b
- c = Node() # / \
- # c root
- root.left = a
- root.right = b
- b.left = c
- b.right = root
- # Max recursion depth
- root.count()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement