It sounds likely that the problem would be better addressed by constructing the tree in the proper order than by fixing it afterwords. The basic step should have the form
newtree = Join[{newedges}, {oldtree}]
See Join[{troot -> broot}, branch, tree]
in addbranch
below.
Example:
The basic data structure in the construction consists of the edges of the tree and a distinguished vertex, the root. It is convenient to carry along the root in the computation. I used the head \[FormalT]
for the data structure; one could use List
, but it can be convenient to have a different head. One slick initialization has more to do with my example than the OP's problem. The OP does not really specify the problem but only alludes to wanting to add from the top. The form of the input is unspecified and the order of the vertices seems random (the 4
-5
edge is in the reverse order of the 6
-2
edge, etc.). The initialization is done as needed by twig
and ramify
. Given uninitialized "leaves", ramify
first converts them to trees (leaves
). I used a simple form of input in which each branch has the form
{root, branch1, branch2, ...}
where each branch may be another such structure or a simple leaf. For instance {8, 3, 7}
represents a tree with root 8
and branches/leaves 3
and 5
. If we replace List
by ramify
, we get ramify[8, 3, 7]
. The first step in computing ramify[8, 3, 7]
is the initialization step
The output is
The OP's tree is specified by
{1, {4, 5}, {6, 2}, {8, 3, 7}}
Code:
ClearAll[addbranch, ramify, twig];
addbranch[\[FormalT][tree, troot_], \[FormalT][branch_, broot_]] :=
\[FormalT][Join[{troot -> broot}, branch, tree], troot];
twig[t_\[FormalT]] := t;
twig[t_] := \[FormalT][{}, t];
ramify[root_, leaves__] :=
ramify[root, Sequence @@ Map[twig, {leaves}]];
ramify[root_, branches__\[FormalT]] :=
Fold[addbranch, \[FormalT][{}, root], {branches}]
Example:
tree = {1, {4, 5}, {6, 2}, {8, 3, 7}} /. List -> ramify
TreePlot[
First[tree],
Left,
Last[tree],
VertexLabeling -> True]