Tree
Details and Options
- Tree objects represent rooted, ordered, labeled trees with leaves. Standard examples include XML, JSON, file systems and Wolfram Language notebooks and expressions.
- Tree[a,…] displays in a notebook as a plot of a tree graph with root node containing data a, with children nodes containing data b, c, …:
- Trees can simultaneously express a hierarchy of nodes and store general data in each node, such as XMLElement or Cell expressions.
- In Tree[data,subtrees], the subtrees are other Tree expressions or general expressions that are interpreted as leaves.
- Tree[…] is always converted to a standard form with structure Tree[data,subtrees].
- Tree[subtrees] is equivalent to Tree[Null,subtrees].
- Tree is treated as a raw object by functions like AtomQ.
- A node containing data is represented as Tree[data,subtrees].
- A tree of the form Tree[data,None] is called a leaf. All other trees are of the form Tree[data,{…}] or Tree[data,<|…|>], corresponding to inner nodes with a list or association of children.
- TreeGraph returns a Graph object representing a tree globally as a list of oriented edges between distinct vertices. Tree represents nested subtrees, each containing an independent data expression.
- Options affecting individual tree elements or nodes include:
- Tree has the same options as Graphics, with the following additions and changes:
-
FormatType StandardForm the default format type for text MaxDisplayedChildren $MaxDisplayedChildren maximum number of children to display ParentEdgeLabel Automatic labels and label placement for edges ParentEdgeLabelFunction Automatic generate labels for edges ParentEdgeLabelStyle Automatic styles for edge labels ParentEdgeShapeFunction Automatic generate graphic shapes for edges ParentEdgeStyle Automatic styles for edges ParentEdgeStyleFunction Automatic generate styles for edges PerformanceGoal Automatic aspects of performance to try to optimize TreeElementCoordinates Automatic coordinates for subtree elements TreeElementLabel Automatic labels for subtree elements TreeElementLabelFunction Automatic generate labels for subtree elements TreeElementLabelStyle Automatic styles for subtree element labels TreeElementShape Automatic graphic shapes for subtree elements TreeElementShapeFunction Automatic generate graphic shapes for subtree elements TreeElementSize Automatic sizes of subtree elements TreeElementSizeFunction Automatic generate sizes of subtree elements TreeElementStyle Automatic styles for subtree elements TreeElementStyleFunction Automatic generate styles for subtree elements TreeLayout Automatic how to lay out subtrees and edges -
AlignmentPoint Center the default point in the graphic to align with AspectRatio Automatic ratio of height to width Axes False whether to draw axes AxesLabel None axes labels AxesOrigin Automatic where axes should cross AxesStyle {} style specifications for the axes Background None background color for the plot BaselinePosition Automatic how to align with a surrounding text baseline BaseStyle {} base style specifications for the graphic ContentSelectable Automatic whether to allow contents to be selected CoordinatesToolOptions Automatic detailed behavior of the coordinates tool Epilog {} primitives rendered after the main plot FormatType TraditionalForm the default format type for text Frame False whether to put a frame around the plot FrameLabel None frame labels FrameStyle {} style specifications for the frame FrameTicks Automatic frame ticks FrameTicksStyle {} style specifications for frame ticks GridLines None grid lines to draw GridLinesStyle {} style specifications for grid lines ImageMargins 0. the margins to leave around the graphic ImagePadding All what extra padding to allow for labels etc. ImageSize Automatic the absolute size at which to render the graphic LabelStyle {} style specifications for labels Method Automatic details of graphics methods to use PlotLabel None an overall label for the plot PlotRange All range of values to include PlotRangeClipping False whether to clip at the plot range PlotRangePadding Automatic how much to pad the range of values PlotRegion Automatic the final display region to be filled PreserveImageOptions Automatic whether to preserve image options when displaying new versions of the same graphic Prolog {} primitives rendered before the main plot RotateLabel True whether to rotate y labels on the frame Ticks Automatic axes ticks TicksStyle {} style specifications for axes ticks
List of all options
Examples
open all close allBasic Examples (5)
Tree[a, {b, c}]Tree[a, {Tree[b, {c, d}], e, f}]A tree with data only in the leaves:
Tree[{Tree[{1, 2}], Tree[{3, 4}]}]A tree containing another tree as data:
Tree[Tree[a, {b, c, d}], {e, f, g}]Tree[<|a -> 1, b -> 2, c -> 3|>]Scope (4)
Represent a leaf with no child:
Tree[a, None]Represent an inner node with no children:
Tree[a, {}]Tree[a, <||>]Specify the children in a list:
Tree[a, {Tree[b, {c, d}], e}]Specify children in an association:
Tree[a, <|"x" -> Tree[b, <|"p" -> c, "q" -> d|>], "y" -> e|>]Options (11)
Styling Individual Tree Elements (2)
Specify the label for the generated tree element:
Tree[a, {b, c}, TreeElementLabel -> "?"]Specify labels and styles for subtrees by position:
Tree[1, {[image], [image], [image]},
TreeElementLabel -> {___, _ ? EvenQ} -> None, TreeElementStyle -> {___, _ ? OddQ} -> {LightRed, EdgeForm[{Red, Dashed}]}]Styling Entire Tree (4)
Specify labels and styles for all subtrees:
Tree[1, {[image], [image], [image]},
TreeElementLabel -> All -> None, TreeElementStyle -> All -> EdgeForm[Red]]Tree[6, {[image], [image]}, BaseStyle -> LightRed]Specify the style for both the edges and the edges of the tree elements:
Tree[6, {[image], [image]}, BaseStyle -> {Dashed, EdgeForm[{Dashing[{}], Thick}]}]Specify the base style and styles for individual tree elements:
Tree[6, {[image], [image]}, BaseStyle -> {Red, EdgeForm[None]}, TreeElementStyle -> All -> Opacity[0]]Tree Layout and Graphics Options (3)
Specify the orientation for the root:
Tree[1, {[image], [image]}, TreeLayout -> Bottom]Tree[{[image], [image], [image]}, TreeLayout -> "BalloonEmbedding"]Specify Graphics options:
Tree[a, {b, c}, Background -> LightBlue, ImageSize -> 50]Elision (2)
Display all children of the root node:
Tree[Range[15], MaxDisplayedChildren -> Infinity]Tree[Range[15], MaxDisplayedChildren -> 5]Display two children for all nodes:
Tree[0, {[image], [image], 3}, MaxDisplayedChildren -> All -> 2]Applications (8)
Import["ExampleData/paintings.xml"]Create a tree from the hierarchy of tags, attributes and elements:
ExpressionTree[%, "XML", IconizedObject[«options»]]Convert an XML tree to symbolic XML:
TreeExpression[%, "XML"]ImportString["{\"Hydrogen\":{\"AtomicNumber\":1,\"AtomicWeight\":1.00793},\"Helium\":{\"AtomicNumber\":4.00259,\"AtomicWeight\":2},\"Lithium\":{\"AtomicNumber\":3,\"AtomicWeight\":6.94141}}", "JSON"]Create a tree from the hierarchy of names and values:
ExpressionTree[%, "JSON"]Convert a JSON tree to symbolic JSON:
TreeExpression[%, "JSON"]childTaxa[ent_] := Replace[ent[EntityProperty["Species", "SubEntities"]], _Missing -> {}];tree = NestTree[childTaxa, Entity["Species", "Kingdom:Animalia"], 2, IconizedObject[«options»]]children[ent : Entity["Person", _]] := Replace[ent[EntityProperty["Person", "Children"]], _Missing -> {}];
children[_] = {};NestTree[children, Entity["Person", "QueenElizabethII::f5243"], 2]Create a tree from the hierarchy of subdirectories and files in a directory:
NestTree[FileNames[All, #]&, FileNameJoin[{$InstallationDirectory, "Documentation"}], 2, FileBaseName]Define a function that converts a TextElement object to a tree:
textElementTree[TextElement[{elem_}]] := textElementTree[elem];
textElementTree[te_TextElement] := NestTree[textElementChildren, te, Infinity, textElementData];Define a function that yields the child elements of a TextElement:
textElementChildren[TextElement[elems_List, RepeatedNull[_, 1]]] := elems;
textElementChildren[TextElement[elem_, RepeatedNull[_, 1]]] := {elem};
textElementChildren[text_String] := {};Define a function that extracts the "GrammaticalUnit" from a TextElement:
textElementData[TextElement[_]] := Null;
textElementData[TextElement[_, prop_]] := CanonicalName[prop["GrammaticalUnit"]];
textElementData[text_String] := text;Create a tree from the hierarchy of properties and text:
textElementTree[TextStructure["Time flies like an arrow."]]Convert a text tree to a TextElement:
TreeFold[{TextElement[#2, <|"GrammaticalUnit" -> #|>]&, #&}, %]Get a list of US cities with populations over 100,000:
largeCities = CityData[{Large, "UnitedStates"}];Construct a graph giving the hierarchical clustering of the cities according to their geodetic positions:
GeoPosition[largeCities]clusteringGraph = ClusteringTree[largeCities]Convert the clustering hierarchy from a Graph object to a Tree object:
clusteringTree = GraphTree[clusteringGraph]For each leaf, obtain the geodetic position of a city from its index in the hierarchical clustering graph:
gps[cityIndex_] := Tree[GeoPosition[Lookup[AnnotationValue[clusteringGraph, "LeafLabels"], cityIndex]], None]For each subtree representing a cluster, give the tree containing the spatial median of its children:
gps[clusterIndex_, children_] := Tree[SpatialMedian[TreeData /@ children], children]Obtain a tree of geodetic positions by using the position of a city for each leaf and the spatial median of the positions for each cluster:
positionTree = TreeFold[{gps, gps}, clusteringTree]Show the edges in this tree of geodetic positions on a map of the United States:
GeoGraphics[Line[Graph[EdgeList[TreeGraph[positionTree]] /. {pos1_, _}{pos2_, _} :> pos1pos2]], GeoBackground -> "VectorBusiness"]tree = RulesTree[Rule[...]];TreeSize[tree]Create an association giving the dates of birth:
birthDates = <|...|>;Define a function that compares two people, giving the person who was younger when they had their first child, together with that child and their age when that child was born:
youngerParent[{parent1_, firstChild1_, age1_}, {parent2_, firstChild2_, age2_}] := If[age1 < age2, {parent1, firstChild1, age1}, {parent2, firstChild2, age2}]Define a function that compares two siblings, giving the older sibling together with their date of birth, in addition to the youngest first-time parent among their descendants:
youngestParentOlderChild[{parent1_, firstChild1_, age1_, child1_, date1_}, {parent2_, firstChild2_, age2_, child2_, date2_}] := Join[youngerParent[{parent1, firstChild1, age1}, {parent2, firstChild2, age2}], If[date1 < date2, {child1, date1}, {child2, date2}]]Define a function that gives the youngest first-time parent among a person's descendants, given the results for their children:
youngestParent[ent_, list_] := Module[{youngest, first, ageYoungest, oldest, dateOldest, date, age},
{youngest, first, ageYoungest, oldest, dateOldest} = Fold[youngestParentOlderChild, {_, _, Quantity[Infinity, "Years"], _, InfiniteFuture}, list];date = Lookup[birthDates, ent];age = DateDifference[date, dateOldest, Quantity[1, "Years"]];Join[youngerParent[{ent, oldest, age}, {youngest, first, ageYoungest}], {ent, date}]]Find the youngest first-time parent in the tree, together with their first child and their age when the child was born:
TreeFold[youngestParent, tree]~Take~3Properties & Relations (6)
A node of a tree does not need to have data:
Tree[{Plus, 1, 1}]RulesTree returns a Tree expression:
RulesTree[a -> {b -> {c, d}, e}]Check whether an expression with head Tree is a valid Tree object:
Tree[a, {b, c}]TreeQ[%]This is not a valid Tree object:
Tree[a, b]TreeQ[%]However, this is a valid Tree object that contains a child with an invalid Tree expression as data:
Tree[c, {Tree[a, b]}]TreeQ[%]%%//InputFormConstruct a Tree expression with ExpressionTree:
ExpressionTree[f[a, b, g[x, y]]]Construct a Tree expression with GraphTree:
GraphTree[[image]]Related Guides
Text
Wolfram Research (2021), Tree, Wolfram Language function, https://reference.wolfram.com/language/ref/Tree.html (updated 2022).
CMS
Wolfram Language. 2021. "Tree." Wolfram Language & System Documentation Center. Wolfram Research. Last Modified 2022. https://reference.wolfram.com/language/ref/Tree.html.
APA
Wolfram Language. (2021). Tree. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/Tree.html
BibTeX
@misc{reference.wolfram_2026_tree, author="Wolfram Research", title="{Tree}", year="2022", howpublished="\url{https://reference.wolfram.com/language/ref/Tree.html}", note=[Accessed: 13-June-2026]}
BibLaTeX
@online{reference.wolfram_2026_tree, organization={Wolfram Research}, title={Tree}, year={2022}, url={https://reference.wolfram.com/language/ref/Tree.html}, note=[Accessed: 13-June-2026]}