Binary Trees for Equations

Hi everyone,
I want to represent an equation like a binary tree,
e,g., I have this equation x**2+x+1
and in Julia I want to represent it as a tree with nodes
e.g. + sign is a Node in that tree or x is Node or 1 is another Node.
Please comment on how I can do this in Julia?

Thanks in advance

:(x^2 + x + 1) returns an Expr object which is exactly a syntax tree for that expression. (Julia syntax for exponentiation is x^2, not x**2 as in Python or Fortran.)

What are you trying to accomplish?

1 Like

Thanks for the kind answer,
I have many equations like this, and I want to calculate the depth of their corresponding trees.

To plot any tree or any other graph type you should install a few packages.
In this particular case, this is the code that defines and plots the binary tree associated to the expression x^2+x+1:

using Graphs, NetworkLayout, GraphPlot
A=[0 1 1 1  0  0; 
   0 0 0 0  1 1;
   0 0 0 0 0 0;
   0 0 0 0 0 0;
   0 0 0 0 0 0;
   0 0 0 0 0 0;]
nodelabel=["+", "*", "x", "1", "x", "x"]
G = DiGraph(A);
node_pos = buchheim(G.fadjlist)
xn, yn =  getindex.(node_pos, 1),  getindex.(node_pos, 2)
gplot(G, xn, -yn; nodelabel=nodelabel,  NODELABELSIZE=6)

To control the plot aesthetics inspect the kwargs that can be passed to gplot as follows:

?gplot

tree-graph-plot

I’m not sure that this is the tree you expected. It’s for the first time when I learn that there exists a tree associated to an expression.

I suggest you take a look at the manual page on expressions. You can define a recursive function depth(ex::Expr) which uses the attributes ex.head and ex.args