I suggest drawing a tree line. You do this using some kind of moving "drawing cursor".
You can save the width attribute for each node, which is calculated as follows:
- vacation
width - 1 width inner node is the sum of all width s of children
Then you draw the root โin the first lineโ in the middle, which means that you just shorten the width half.
Then you create a grid above the image, so that each grid line corresponds to one line, respectively. one step from left to right, and each intersection of the grid lines can contain a node, and each node has enough space.
Then you iterate over the children and, iterate over, you accumulate the children width and draw the children "in the next line." To draw currentChild , you move the draw cursor currentWidth/2 to the right, draw currentChild and move the draw cursor to the remaining currentWidth/2 to the right.
To get the nodes in good order, you can consider the first width search.
I hope my explanations are clear, but I think it would be better if I draw a little.
This is our tree ( x - nodes, all other edges)
+-------x--+-------+ | | | +-x-+ +-+x+-+ +-x-+ | | | | | | | | | xxxxxxxxx
So you compute sheet width s:
+-------x--+-------+ | | | +-x-+ +-+x+-+ +-x-+ | | | | | | | | | 1 1 1 1 1 1 1 1 1
Then, from bottom to top, width as the sum of the child width s:
+-------9--+-------+ | | | +-2-+ +-+4+-+ +-3-+ | | | | | | | | | 1 1 1 1 1 1 1 1 1
So, you start at the root ( width 9) and follow the 4.5 steps to rigt in the first line.
Then you move the "drawing cursor" to the second row, "column 0" (go left).
The first child has a width 2, so we will direct the grid lines 2/2 2/2=1 the right and draw a node and move the drawing cursor to the remaining 1 grid lines to the right to end the node. So, the next node has a width 4, which means we go right 4/2 = 2 grid lines, draw, go the remaining 2 steps, etc.
And so on with the next line. At the end (or in intermediate steps), connect the nodes.
This procedure ensures that there are no overlapping nodes (if the grid lines are far enough apart), but this can lead to the creation of rather large tree diagrams that could use the space more efficiently.
To detect unused space, you can simply scan the lines after the process described above and see if there are any intersecting grid lines and, possibly, rebuild some nodes to fill the gap.