Skip to content
Advertisement

How to nicely lay out a tree in the form of a table (using merged cells)

Background: I have some data that I want to present in a table. Each column in the table has a header. Some of these headers in turn, have common headers. In other words, I have a tree of headers that I want to show in the table cells.

Problem: How to nicely lay out a tree in the form of table by means of merging cells (cf merged cells in Excel or rowspan / colspan in HTML tables)?

Some requirements:

Given a tree like the following:

JavaScript
  • The resulting table should always be rectangular, i.e. this is not acceptable:

    JavaScript
  • The height of the cells should be as evenly distributed as possible. (There should be no unecessary height constraints between siblings.) For instance solving the above situation by simply letting the leaves grow downwards like this is not acceptable:

    JavaScript
  • The correct output should look something like this:

    JavaScript
  • The number of rows used should be minimized. In other words, the right version is preferred over the left version below:

    JavaScript

Advertisement

Answer

As usual, explaining the problem carefully seem to have helped. I believe I figured it out. The key idea is to traverse the tree recursively and (among a few other things) compute the least common multiple of the depths of all subtrees in each step.

The answer is written in Java but it should be trivial to rewrite into PHP, C# or what-have-you. It refers to the following two auxiliary classes and targets HTML-tables.

JavaScript

The solution is broken up in two parts:

  1. Conversion from Tree to List<Cell>.

  2. Layout of List<Cell> to a proper <table>...</table>.

    (Presumably not required if targetting for instance a spread-sheet.)

Conversion from Tree to List<Cell>

This is done using the methods rowsToUse and getCells defined below. The former computes the total number of rows required to lay out a given tree, and the latter generates the actual Cells. The arguments denote the following:

  • t is the root of the tree for which Cells should be generated.
  • row and col denotes the current row and column of the top-most (root) cell.
  • rowsLeft specifies how many rows the current tree should be distributed on.

Here are the two methods:

JavaScript

The methods depth, width and lcm are straight forward. See full source at the bottom if you like.

Layout of List<Cell> to a proper <table>...</table>

JavaScript

Full source and demo.

Here’s the full source. Given the tree

JavaScript

it produces the following table body:

JavaScript

which looks like

enter image description here

Full source:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement