Can one display the position of each character in an expression tree? For instance: g[h[i, h], l] should be displayed using TreeForm where each character is replaced by its position in the tree. I can mimic this with TreeForm[0[10[11, 120[121, 122]], 2]]. However, I want the true representation of the positions (using the usual list notation for positions, i.e. {0} instead of 0, {1,0} instead of 10 etc. Is there a way to apply the Position function to each such character in the tree and display the positions in TreeForm?


1 Answer 1


Perhaps you can convert the heads to the desired strings using MapIndexed:

TreeForm @ MapIndexed[
    ToString @* Last,

enter image description here

  • $\begingroup$ Thanks. This does the trick. Is it possible to just apply matters in one go, i.e. avoiding the need to use both {-1} (i.e. the leaves) and Heads -> True (to apply it to internal nodes, i.e. non-leaves). In other words, is there a way to apply something directly to all nodes of the expression tree? Or is Mathematica set up to distinguish strictly between leaves and internal nodes? (As seems to be the case from its convention to drop the final zero in the leaf positions). $\endgroup$
    – Michel
    Apr 22, 2019 at 21:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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