Can trees be made into graphs?
You can use halirutan's makeTree
function from this answer. Your purpose is slightly different than the purpose in that question, so the function can be simplified a bit in this context:
makeTree[nodes_] := Module[{counter = 0},
traverse[h_[childs___]] := With[{id = counter},
{DirectedEdge[id, ++counter], traverse[#]} & /@ {childs}
];
traverse[_] := Sequence[];
TreeGraph[#, GraphLayout -> "LayeredDigraphEmbedding"] &@Flatten[traverse[nodes]]
]
Use it like this:
expr = TreeForm[{a, {a, {a, a, a}}}];
{expr, makeTree @@ expr}
TreeFormToGraph[treeForm_] :=
Module[{tree = ToExpression@ToBoxes@treeForm, order, pos, label},
label = Cases[tree, Inset[name_, n_] :> Rule[n, Placed[name, Center]],Infinity];
{order, pos} = Catenate /@ Cases[tree,
Line[order_] | GraphicsComplex[pos_, ___] :> {order, pos}, Infinity];
Graph[UndirectedEdge @@@ order, VertexLabels -> label,
VertexCoordinates -> MapIndexed[Rule[First[#2], #] &, pos]]]
Note the result of TreeFormToGraph
is Graph
object.
Example 1:
Example 2:
Update: We can use GraphComputation`ExpressionGraph
to get a one-liner that converts a TreeForm
object to a Graph
object:
treeFormToGraph = Apply[GraphComputation`ExpressionGraph];
treeFormToGraph @ TreeForm[{{{a,b},c},d}]
We can add styling to get a Graph
that looks like TreeForm
:
ClearAll[treeFormToGraph ]
treeFormToGraph[t_TreeForm, o : OptionsPattern[]] :=
Module[{g = GraphComputation`ExpressionGraph[t[[1]], o,
VertexSize -> {"Scaled", .1}, VertexStyle -> LightYellow,
VertexShapeFunction -> "Rectangle"]},
SetProperty[g, VertexLabels -> (PropertyValue[g, VertexLabels] /.
Rule[a_, b_] :> Rule[a, Placed[b, Center]])]];
treeFormToGraph[TreeForm[{{{a,b},c},d}], VertexStyle->Pink]
Original answer:
We can use, instead of TreeForm
, GraphComputation`ExpressionGraph
which produces a Graph
object accepting all the options of Graph
.
g1 = GraphComputation`ExpressionGraph[{{{a, b}, c}, d},
VertexSize -> {"Scaled", .1}, VertexStyle -> LightYellow,
VertexShapeFunction -> "Rectangle"];
SetProperty[g1, VertexLabels -> (PropertyValue[g1, VertexLabels] /.
Rule[a_, b_] :> Rule[a, Placed[b, Center]])]