3

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?

Najib Idrissi
  • 576
  • 3
  • 11

2 Answers2

5
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

Bob Hanlon
  • 157,611
  • 7
  • 77
  • 198
2

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} *)

Najib Idrissi
  • 576
  • 3
  • 11