def get_ancestor(taxid, tree, stop_nodes):
    """Walk up tree until reach a stop node, or root."""
    t = taxid
    while True:
        if t in stop_nodes:
            return t
        elif not t or t == tree[t]:
            return t  # root
        else:
            t = tree[t]