Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8409347
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T23:53:01+00:00 2026-06-09T23:53:01+00:00

Background: I have some data that I want to present in a table. Each

  • 0

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:

+ Header 1
|---+ Header 2
|   |---- Header 4
|   '---+ Header 5
|       |---- Header 8
|       '---- Header 9
'---+ Header 3
    |---- Header 6
    '---- Header 7
  • The resulting table should always be rectangular, i.e. this is not acceptable:

    .-------------------------------------------.
    |                  Header 1                 |
    +--------------------------+----------------+
    |    Header 2              |    Header 3    |
    +----------+---------------+--------+-------+
    | Header 4 |   Header 5    |  Hdr 6 | Hdr 7 |
    '----------+-------+-------+--------+-------'
               | Hdr 8 | Hdr 9 |
               '-------+-------'
    
  • 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:

    .-------------------------------------------.
    |                  Header 1                 |
    +--------------------------+----------------+
    |    Header 2              |    Header 3    |
    +----------+---------------+--------+-------+  <-- Height of Header 3
    |          |   Header 5    |        |       |      constrained by
    | Header 4 +-------+-------+  Hdr 6 | Hdr 7 |      height of Header 2
    |          | Hdr 8 | Hdr 9 |        |       |
    '----------+-------+-------+--------+-------'
    
  • The correct output should look something like this:

    .-------------------------------------------.
    |                  Header 1                 |
    +--------------------------+----------------+
    |    Header 2              |    Header 3    |
    +----------+---------------+                |
    | Header 4 |   Header 5    |--------+-------+  <-- constraint relaxed.
    |          +-------+-------+  Hdr 6 | Hdr 7 |
    |          | Hdr 8 | Hdr 9 |        |       |
    '----------+-------+-------+--------+-------'
    
  • The number of rows used should be minimized. In other words, the right version is preferred over the left version below:

    .--------------------------.         .--------------------------.
    |  Rowspan 3               |         |  Rowspan 1               |
    +-------------+------------+         +-------------+------------+
    |  Rowspan 4  | Rowspan 6  |   -->   |  Rowspan 2  | Rowspan 3  |
    +-------------+            |         +-------------+            |
    |  Rowspan 6  +------------+         |  Rowspan 3  +------------+
    |             | Rowspan 4  |         |             | Rowspan 2  |
    '-------------+------------'         '-------------+------------'
    
    Unecessarily large rowspans.             Minimized rowspans.
      (actual height: 13 rows)             (actual height: 6 rows)
    
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T23:53:03+00:00Added an answer on June 9, 2026 at 11:53 pm

    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.

    class Tree {
        String val;
        Tree[] children;
        ...
    }
    
    class Cell {
        String val;
        int row, col, rowspan, colspan;
        ...
    }
    

    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:

    public static int rowsToUse(Tree t) {
        int childrenRows = t.children.length == 0 ? 0 : 1;
        for (Tree child : t.children)
            childrenRows = lcm(childrenRows, rowsToUse(child));
        return 1 + childrenRows;
    }
    
    
    public static List<Cell> getCells(Tree t, int row, int col, int rowsLeft) {
    
        // Add top-most cell corresponding to the root of the current tree.
        int rootRows = rowsLeft / rowsToUse(t);
        List<Cell> cells = new ArrayList<Cell>();
        cells.add(new Cell(t.val, row, col, rootRows, width(t)));
    
        // Generate cells for subtrees.
        for (Tree child : t.children) {
            cells.addAll(getCells(child, row+rootRows, col, rowsLeft-rootRows));
            col += width(child);
        }
    
        return cells;
    }
    

    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>

    public static String getHtmlTable(List<Cell> cells) {
    
        // Sort the cells primarily on row, secondarily on column.
        Collections.sort(cells, new Comparator<Cell>() {
            public int compare(Cell c1, Cell c2) {
                int pri = Integer.valueOf(c1.row).compareTo(c2.row);
                int sec = Integer.valueOf(c1.col).compareTo(c2.col);
                return pri != 0 ? pri : sec;
            }
        });
    
        // Lay out the cells row by row.
        StringBuilder result = new StringBuilder("<table><tbody>");
        for (int row = 0, i = 0; i < cells.size(); row++) {
            result.append("<tr>\n");
            for (; i < cells.size() && cells.get(i).row == row; i++)
                result.append(cells.get(i).asTdTag());
            result.append("</tr>\n");
        }
        return result.append("</tbody></table>").toString();
    }
    

    Full source and demo.

    Here’s the full source. Given the tree

    Tree t = new Tree("1",
               new Tree("2",
                 new Tree("4"),
                   new Tree("5",
                     new Tree("8"),
                     new Tree("9"))),
               new Tree("3",
                 new Tree("6"),
                 new Tree("7")));
    

    it produces the following table body:

    <tr><td colspan='5'>1</td></tr>
    <tr><td colspan='3' rowspan='2'>2</td><td colspan='2' rowspan='3'>3</td></tr>
    <tr></tr>
    <tr><td rowspan='4'>4</td><td colspan='2' rowspan='2'>5</td></tr>
    <tr><td rowspan='3'>6</td><td rowspan='3'>7</td></tr>
    <tr><td rowspan='2'>8</td><td rowspan='2'>9</td></tr>
    

    which looks like

    enter image description here

    Full source:

    import java.io.*;
    import java.util.*;
    
    class Tree {
    
        String val;
        Tree[] children;
    
        public Tree(String val, Tree... children) {
            this.val = val;
            this.children = children;
        }
    }
    
    
    class Cell {
        String val;
        int row, col, rowspan, colspan;
        public Cell(String val, int row, int col, int rowspan, int colspan) {
            this.val = val;
            this.row = row;
            this.col = col;
            this.rowspan = rowspan;
            this.colspan = colspan;
        }
    
        public String asTdTag() {
            String cs = colspan == 1 ? "" : " colspan='" + colspan + "'";
            String rs = rowspan == 1 ? "" : " rowspan='" + rowspan + "'";
            return "<td" + cs + rs + ">" + val + "</td>";
        }
    }
    
    
    public class TreeTest {
    
        public static int rowsToUse(Tree t) {
            int childrenRows = t.children.length == 0 ? 0 : 1;
            for (Tree child : t.children)
                childrenRows = lcm(childrenRows, rowsToUse(child));
            return 1 + childrenRows;
        }
    
    
        public static List<Cell> getCells(Tree t, int row, int col, int rowsLeft) {
    
            // Add top-most cell corresponding to the root of the current tree.
            int rootRows = rowsLeft / rowsToUse(t);
            List<Cell> cells = new ArrayList<Cell>();
            cells.add(new Cell(t.val, row, col, rootRows, width(t)));
    
            // Generate cells for subtrees.
            for (Tree child : t.children) {
                cells.addAll(getCells(child, row+rootRows, col, rowsLeft-rootRows));
                col += width(child);
            }
    
            return cells;
        }
    
    
        public static int width(Tree t) {
            if (t.children.length == 0)
                return 1;
            int w = 0;
            for (Tree child : t.children)
                w += width(child);
            return w;
        }
    
    
        public static int lcm(int a, int b) {
            int c = a * b;
            while (b > 0) {
                int t = b;
                b = a % b;
                a = t;
            }
            return c / a;
        }
    
    
        public static String getHtmlTable(List<Cell> cells) {
    
            // Sort the cells primarily on row, secondarily on column.
            Collections.sort(cells, new Comparator<Cell>() {
                public int compare(Cell c1, Cell c2) {
                    int pri = Integer.valueOf(c1.row).compareTo(c2.row);
                    int sec = Integer.valueOf(c1.col).compareTo(c2.col);
                    return pri != 0 ? pri : sec;
                }
            });
    
            // Lay out the cells row by row.
            StringBuilder result = new StringBuilder("<table><tbody>");
            for (int row = 0, i = 0; i < cells.size(); row++) {
                result.append("<tr>\n");
                for (; i < cells.size() && cells.get(i).row == row; i++)
                    result.append("  " + cells.get(i).asTdTag() + "\n");
                result.append("</tr>\n");
            }
            return result.append("</tbody></table>").toString();
        }
    
    
        public static void main(String[] args) throws IOException {
    
            Tree t = new Tree("1",
                    new Tree("2",
                      new Tree("4"),
                        new Tree("5",
                          new Tree("8"),
                          new Tree("9"))),
                    new Tree("3",
                      new Tree("6"),
                      new Tree("7")));
    
            FileWriter fw = new FileWriter("tree.html");
    
            List<Cell> cells = getCells(t, 0, 0, rowsToUse(t));
    
            fw.write("<html><head><style>table, td { border-style: solid; } " +
                     "table { border-spacing: 0px; border-width: 0 0 1px 5px; } " +
                     "td { padding: 15px; text-align: center; " +
                     "border-width: 1px 5px 0 0;} </style></head><body>");
            fw.write(getHtmlTable(cells));
            fw.write("</body></html>");
    
            fw.close();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have some data. I want to go through that data and change cells
This question requires some hypothetical background. Let's consider an employee table that has columns
I have some code that starts a background process for search in my WPF
I have some code that will change the background color of a specific label
let's say that I have some <TR style = background-color : red ;> and
Some background: we have a windows application (c#) that locate in the system try.
I have a background thread and the thread calls some methods that update the
while restoring some data i am displaying a activity indicator..but i want the background
I have some data I need to present to a user in a very
Assume that I have some array of data (a vector to be specific). Can

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.