Skip to content

Instantly share code, notes, and snippets.

@effective-light
Last active June 19, 2017 21:04
Show Gist options
  • Select an option

  • Save effective-light/5998aa907662b53983063e746735dea2 to your computer and use it in GitHub Desktop.

Select an option

Save effective-light/5998aa907662b53983063e746735dea2 to your computer and use it in GitHub Desktop.
148 exam practice
class BTNode:
def __init__(self, value=None, left=None, right=None):
self.value, self.left, self.right = value, left, right
def count_leaves(root: 'BTNode') -> int:
""" Return the number of leaves in the tree rooted at root.
>>> count_leaves(None)
0
>>> count_leaves(BTNode(0, None, None))
1
>>> count_leaves(BTNode(0, BTNode(1, BTNode(BTNode(3), BTNode(4))), BTNode(2)))
"""
if not root:
return 0
if not root.left and not root.right:
return 1
count = 0
if root.left:
count += count_leaves(root.left)
if root.right:
count += count_leaves(root.right)
return count
class Node:
"""Node in a linked list"""
def __init__(self: 'Node', value: object, next: 'Node' = None) -> None:
"""Create Node self with data value and successor next."""
self.value, self.next = value, next
class LinkedList:
"""Collection of Nodes to form a linked list"""
def __init__(self: 'LinkedList') -> None:
"""Create empty LinkedList"""
self.front, self.back, self.size = None, None, 0
def remove_last(self: 'LinkedList') -> None:
""" Remove last node of self.
>>> lst = LinkedList()
>>> back = Node(3)
>>> lst.front = Node(2, Node(5, Node(7, back)))
>>> lst.back = back
>>> lst.remove_last()
>>> lst.remove_last()
>>> lst.back.value
5
"""
current = self.front
while current.next is not self.back:
current = current.next
self.back = current
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment