Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Begin exam Code by Prof. Danny Heap
- class BTNode:
- """Node in a binary tree"""
- def __init__(self: 'BTNode', value: object, left: 'BTNode',
- right: 'BTNode') -> None:
- """
- Create a new BTNode with value and (possibly)
- children left and right.
- """
- self.value, self.left, self.right = value, left, right
- def count_nodes(n: BTNode) -> (int, int):
- """
- Return a tuple containing the number of interior nodes and the number
- of leaves in the tree rooted at n, or (0,0) if n is None.
- <Test cases go here>
- """
- # Begin student code
- if not n: return 0, 0 # this is a line of code[added when checking answers]
- if not n.left and not n.right:
- return 0, 1
- else:
- left_count = (0, 0)
- right_count = (0, 0)
- if n.left:
- left_count = count_nodes(n.left)
- left_count[0] += 1
- if n.right:
- right_count = count_nodes(n.right)
- right_count[0] += 1
- return left_count[0] + right_count[0], left_count[1] + right_count[1]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement