def size(n): sz = 0 if n: if not hasattr(n, "size"): if is_leaf(n): n.size = 1 else: n.size = size(n.left) + 1 + size(n.right) sz = n.size return sz
def pop_leaf(node): """ pop last added leaf. pop_leaf(heap) -> (new_heap, poped_node) """ if is_leaf(node): return None, node if is_pop_from_left(node): child = left(node) set_fun = set_left else: child = right(node) set_fun = set_right if is_leaf(child): node = set_fun(node, None) return (node, child) else: child, poped = pop_leaf(child) node = set_fun(node, child) return (node, poped)