3
$\begingroup$

With the Tree function, I can draw arbitrary trees:

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

enter image description here

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

enter image description here

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?

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

2 Answers 2

5
$\begingroup$
children[ent : Entity["Person", _]] := Replace[ent[EntityProperty["Person", "Children"]], _Missing -> {}]; children[_] = {}; NestTree[children, Entity["Person", "QueenElizabethII::f5243"], 2, ImageSize -> 1000] 

enter image description here

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

enter image description here

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}]}] 

enter image description here

bottomsUp[origtree] 

enter image description here

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

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} *) 
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.