I would like to display a binary tree using something analogous to TableForm
. For example, a small such tree is given by this array (which except for the root still needs to be populated):
x = {{3}, {0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}}.
Szabolds's answer to a similar question uses Grid and comes very close to what I need:
With[
{r = Riffle[#, ""] & /@ arr},
{l = Max[Length /@ r]},
Grid[CenterArray[#, l, ""] & /@ r]
]
The output of the above code applied to my array looks like this:
The reason it does not work is that, unlike the example this code was written for, except for the root all the rows have an even number of columns. Therefore, to get a nice binary tree look what's needed is to add more space in the higher rows than in the lower rows. The spacing for the lowest row could be made smaller than shown here, and it needs to be doubled for each row above that, up to the second row. The motivation for smaller spacing at the bottom is that I would be able to fit more rows in a standard figure in a report.
I don't know if it's possible to do this with Riffle, e.g. with something like Riffle[x, 2^(n-i)" "]
, where n
is the length of the array and i
is the row number. Here I am multiplying the space " "
by a numerical factor, which I realise is probably nonsense -- just trying to communicate the idea.
I would rather not use TreePlot because I like the economy of the TableForm
or Grid
format.