def midpoint(tree):
    """Calculate tip to tip distances of the provided tree and root it halfway
    between the two longest tips.

    Parameters
    ----------
    tree : TreeNode object
        The tree to be rooted.

    Returns
    -------
    tree_rooted : TreeNode object
        Midpoint rooted input tree.
    """
    longest_dist = None
    dists = tree.distances()
    for pair in dists:
        if not longest_dist or longest_dist < dists[pair]:
            longest_dist = dists[pair]
            node_a, node_b = pair
    if not longest_dist or not node_a or not node_b:
        return tree
    mid_dist = longest_dist / 2.0
    midpoint_node = None
    parent = node_a
    dist_walked = 0
    current_child = None
    while parent:
        dist_walked += parent.dist
        if dist_walked > mid_dist:
            midpoint_node = parent
            break
        for child in parent.children:
            if node_b in child.iter_leaves():
                current_child = child
                break
        parent = parent.parent
    if current_child:
        while current_child:
            dist_walked += current_child.dist
            if dist_walked > mid_dist:
                midpoint_node = current_child
                break
            for child in current_child.children:
                if node_b in child.iter_leaves():
                    current_child = child
    if midpoint_node:
        return tree.reroot(midpoint_node)
    else:
        return tree
