import heapq


def subtree_nodes_with_edge_length(tree, leaf_y, n):
    """ Returns list of length n of leaves closest to sister taxon (minimizing edge weights)
    
    Parameters
    ----------
    tree : treeswift tree object
    leaf_y : treeswift node for closest sister taxon
    n = number of taxa contained in subtree
    
    Returns
    -------
    list of taxon labels corresponding to leaves in the subtree
    """
    queue = [(leaf_y.get_edge_length(), leaf_y.get_parent())]

    leaves = [leaf_y]
    visited = {leaf_y}

    while len(leaves) < n:
        try:
            (length, node) = heapq.heappop(queue)
        except IndexError:
            break

        visited.add(node)
        if node.is_leaf():
            leaves.append(node)

        adjacent_nodes = node.child_nodes()
        if not node.is_root():
            adjacent_nodes.append(node.get_parent())

        for neighbor in adjacent_nodes:
            if neighbor not in visited:
                if neighbor == node.get_parent():
                    heapq.heappush(queue, (length+node.get_edge_length(), neighbor))
                else:
                    heapq.heappush(queue, (length+neighbor.get_edge_length(), neighbor))

    result = []
    for item in leaves:
        result.append(item.get_label())

    return result