Solution (source code)

= Solution

If two lengths differed by at least two, replacing two deepest sibling leaves by their parent and splitting a shallower leaf lowers total length, contradicting optimality. Thus lengths are $b=\lfloor\log_2m\rfloor$ and $b+1$. Kraft equality gives $n_b=2^{b+1}-m$ and $n_{b+1}=2m-2^{b+1}$, hence
$$
\boxed{L=b+2-\frac{2^{b+1}}m.}
$$