def map_subtrees(tree, fn):

    """Returns a tree in which every subtree is mapped by fn.

    fn() is called on each subtree of tree after all of its children
    have been mapped.
    """

    if isinstance(tree, list):
        return fn([map_subtrees(child, fn) if i > 0 else child 
                   for i, child in enumerate(tree)])
    else:
        return fn(tree)