def _append_sorted(root, el, comparator):
    """ Add el as a child of root, or as a child of one of root's children.
    Comparator is a function(a, b) returning > 0 if a is a child of b, < 0 if
    b is a child of a, 0 if neither.
    """
    for child in root:
        rel = comparator(el, child)
        if rel > 0:
            # el fits inside child, add to child and return
            _append_sorted(child, el, comparator)
            return
        if rel < 0:
            # child fits inside el, move child into el (may move more than one)
            _append_sorted(el, child, comparator)
    # we weren't added to a child, so add to root
    root.append(el)
Add el as a child of root, or as a child of one of root's children.
    Comparator is a function(a, b) returning > 0 if a is a child of b, < 0 if
    b is a child of a, 0 if neither.