Let $T$ be a labeled tree with vertices $V = \{1, \dots, n\}$ and edges $E$. Define the length of an edge $e = \{ u, v \}, u \in V, v \in V$ to be $l(e) = |u - v|$, i.e. the distance between the nodes in the linear arrangement of the tree. Let the length sequence $L$ of $T$ be the sorted sequence of lengths of all the edges in $T$.
An example tree is shown below. Each edge is marked with its length. The length sequence for this tree is $(1, 1, 1, 1, 2, 2, 3)$.
My question is: Given a length sequence $L$, is there an efficient algorithm to generate a labeled tree $T$ with length sequence $L$, randomly at uniform from the set of all such trees? Or failing that, to enumerate the set of trees with a given length sequence $L$?
To clarify, here is an extremely inefficient algorithm that does what I want. We have a desired length sequence $L$, let's say (1,1,1,1,2,2,3). To generate a random tree with the desired edge lengths:
- Generate a random labeled tree $T$ on $n=8$ nodes by sampling a random Prüfer code.
- Check if the length sequence of $T$ matches $L=(1,1,1,1,2,2,3)$. If yes, accept $T$. If not, goto 1.
This is very inefficient because there are $n^{n-2}$ possible trees generated in step 1, and only a very small number of those trees matches the desired $L$, especially as the trees get large.
Update: I have an algorithm that seems to work, but it seems like it could be made more efficient.
Algorithm:
Let $T$ be a graph with nodes $V$ and empty edge set $E$.
For each possible edge length $l$ in $\{1, \dots, \text{max}(L)\}$,
Let $k$ be the number of entries in $L$ matching $l$. So for example, if $L=(1,1,1,1,2,2,3)$ and $l=1$, then $k=4$.
If $k=0$, skip to the next $l$.
Generate the set of possible new edges $P = \{(u,v) : u \in V, v \in V, (u,v) \not\in E, u = v+l \text{ or } u = v-l\}$
If $P$ is empty, fail and start over again from 1.
Generate the set $Q$ of all combinations of size $k$ of elements of $P$
Randomly choose an element of $Q$, which is a set of $k$ edges. Add this set of edges to $E$.
If the resulting $T$ is not a forest, fail and start over again from 1. Otherwise, continue to the next $l$.
Basically, this generates the random graphs matching $L$, then filters them to be trees.