Given a tree-like data structure of nodes with each node having a property children that contains the children nodes from left to right, I wish to create a string representation of this data structure such that each "vertical column" of the representation from left to right is a path leading to a leaf node. The first column would be the leftmost path, and the last column would be the rightmost path.
For example, here is an example of how this would look like for a case in which each node's representation is a single character:
Example 1:
Root
├─T
├─E
├─S
├─T─────────┬───┐
├─N─┬───┐ ├─V ├─W
├─A ├─E ├─I ├─A ├─O
├─S ├─X ├─C ├─L ├─W─┐
├─T └─T └─E ├─U ├─H ├─T
└─Y └─E ├─U ├─H
└─H ├─I
├─S
├─I
├─S
├─L
├─O
├─N
└─G
Here is a case in which each node's string representation is a longer string:
Example 2:
Root
├─Apple─────────┐
├─Banana─┐ ├─Elderberry─┬───────┐
└─Cherry └─Date └─Fig └─Grape └─Hazelnut
Given that each line in the above string representations each represent a level (are at a specific height) of the tree, I was under the impression that BFS was the way to go in creating the string representation.
However, as can be seen in the above examples, it does not seem as simple as that since the line depends on the nodes to the left of the current node and the lengths of their string representations. So, my thought is that you may have to combine the BFS with DFS in some way to consider the number of children to the left of the current node. However, I'm struggling in figuring out how one would do this.
This isn't a language-specific question as I am looking for more of a general algorithm that I can adopt to my language of choice. Though, I would appreciate the algorithm being made efficient where possible. Additionally, please assume that tree nodes are immutable and therefore cannot be modified to store additional information for the purposes of this algorithm.