# How to display a tree with a root at the bottom but leaves in left-to-right order?

With the Tree function, I can draw arbitrary trees:

Tree[f, {1, 2, 3}]


However, real trees grow from the ground to the sky. When I pass the TreeLayout -> Bottom option, the leaves become in the wrong order:

How can I make leaves appear in the correct order, in the graphical display of Tree with a root at the bottom? Is there a built-in way to do that, or should I write my own function that reverses leaves on the fly?

• Tree[f, Reverse@{1, 2, 3}, TreeLayout -> Bottom] Commented May 16, 2022 at 22:09

children[ent : Entity["Person", _]] :=
Replace[ent[EntityProperty["Person", "Children"]],
_Missing -> {}];
children[_] = {};

NestTree[children, Entity["Person",
"QueenElizabethII::f5243"], 2, ImageSize -> 1000]


NestTree[Reverse@*children, Entity["Person",
"QueenElizabethII::f5243"], 2, ImageSize -> 1000,
TreeLayout -> Bottom]


EDIT: For the example given in the comment below

bottomsUp[
tree_Tree] := (tree //.
Tree[lbl_, br_List] :> temp[lbl, Reverse@br]) //.
temp :> (Tree[##, TreeLayout -> Bottom] &)


EDIT 2: or a little cleaner

bottomsUp[tree_Tree] := (tree //. Tree[lbl_, br_List] :>
temp[lbl, Reverse@br, TreeLayout -> Bottom]) //.
temp :> Tree

origtree = Tree[Subscript[μ, {1, 2, 3, 4}, {5, 6}],
{Tree[Subscript[μ, {1, 2}, {3, 4}],
{Tree[Subscript[ι, {1}]^{1, 2},
{Subscript[ι, {}]^{1}}], Subscript[ι, {3}]^{3, 4}}],
Tree[Subscript[μ, {5}, {6}], {Subscript[ι, {}]^{6}, id}]}]


bottomsUp[origtree]


• I have multi-level trees that are not generated by NestTree. Your answer is very specific to that function. Commented May 16, 2022 at 22:58
• Then post an example that demonstrates the problem you are experiencing. Commented May 16, 2022 at 23:03

Since there does not appear to be a built-in way to achieve what I want, here is my code (which is maybe a bit simpler than the other answer, although probably less efficient due to recursion):

bottom[t_?TreeLeafQ] := t

bottom[Tree[root_, children_]] :=
Tree[root, bottom /@ Reverse[children], TreeLayout -> Bottom]


Well, seems like my hunch was wrong. My code is about 5x faster:

tree = RandomTree[2000]

RepeatedTiming[bottomsUp[tree];]
(* {0.0446962, Null} *)

RepeatedTiming[bottom[tree];]
(* {0.0088462, Null} *)