Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

For some expressions, TreeForm may grow very long. I'm only interested in the top levels of the expression. How can I get the tree form of only the first levels an expression?

For example: how to get the first levels of this expression in tree form?

Nest[1/(1 + #) (1 - #) &, w, 5]

TreeLevel of the above expression

share|improve this question
up vote 5 down vote accepted

Can use something like this:

showTopTree[expr_, level_] :=
     SetAttributes[myHold, HoldAll];
       HoldAll] @@
    (Hold[#] &@
      DeleteCases[MapAll[myHold, expr], _, {2*level, Infinity}] //.
           myHold[x__] :> x)];

Pretty ugly, but seems to work:

expr = Nest[1/(1 + #) (1 - #) &, w, 5]
Manipulate[showTopTree[expr, n], {n, 1, Depth[expr], 1}]

GraphicsGrid[Partition[showTopTree[expr, #] & /@ Range[6], 3]]

enter image description here

share|improve this answer

You can use the second argument of TreeForm to display and expression to a certain depth, so for your example you could do TreeForm[Nest[1/(1 + #) (1 - #) &, w, 5], 1] (although the result isn't very pretty in this case)

Mathematica graphics


Instead of using TreeForm you could also construct a graph of the expression using ExpressionTreePlot in the GraphUtilities` package and use that to extract the desired subtree.

exprTree[expr_] :=
 Module[{g, edges, labels},
  g = ExpressionTreePlot[expr, Top];
  edges = Rule @@@ Cases[g, Line[a_] :> a, Infinity][[1]];
  labels = Cases[g, Text[a_, b_] :> (b -> a[[1, 1]]), Infinity];
  {edges, labels}]

subTree[expr_, d_, pos_: Top] := Module[{edges, labels, sub},
  {edges, labels} = exprTree[expr];
  sub = NeighborhoodSubgraph[edges, 1, d];
  TreePlot[sub, pos, VertexRenderingFunction ->
    Function[{p, v}, 
     Text[Framed[Style[v /. labels, FontSize -> 10], 
       Background -> Lighter[Gray, .8]], p]]]]


subTree[Nest[1/(1 + #) (1 - #) &, w, 5], 4]

Mathematica graphics

Here, I've chosen the style of VertexRenderingFunction in the definition of subTree to mimic the style of TreeForm but you could choose you own style for displaying the vertex labels.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.