3
I am suffering with the following problem: I want to print in the terminal the "drawing" of a tree.
The algorithm I’m working on is based on a stack. In this stack, I insert values(string or integer) and have the following commands: add, sub, mult and div. These commands take the 2 values that are at the top of the stack and create a tree with the operation, where the root of the tree is the operation and the children are the values.
I can print them on a line, it would be something like: ((5 + 2) - (3 * 1)).
In this example we have as root the operation "-", as children the operations "+" and "*" and as children of addition, 2 and 5, and children of multiplication, 3 and 1.
But I would also like to print "graphically". On the console would come out something like:
|-|
|
|+|-----------|*|
| |
|2|-----|5| |3|-----|1|
The structure of my cell is as follows:
struct T;
typedef struct Temp {
char *data;
struct Temp *next;
struct T *firstChild;
} Node;
typedef struct T {
struct T *next;
Node *child;
} SonNode;
And this is my attempt at printing:
void treeAux( Node *n, int tam ) {
if ( n == NULL ) return;
if ( n == top || n->firstChild == NULL ) addChar(tam, ' ');
printf("|%s|", n->data);
if ( n->firstChild == NULL ) return;
printf("\n");
addChar( tam+1, ' ');
printf("|\n");
SonNode *f = n->firstChild;
while ( f != NULL ) {
if ( f != n->firstChild ) addChar(5, '-');
treeAux( f->child, (int)tam/2 + 6);
if ( f->next == NULL ) return;
f = f->next;
}
}
void tree() {
treeAux( top, 20 );
}
The main problem I’m having is how to control the spacing.
PS.: Top is a reference to the top of the stack. In this case, it would be a Node.
PS2.: Only binary trees are generated at first, but in the future I’d like to add methods that simplify accounts and make the tree generic.
PS3.: The addChar method simply adds times the character passed as parameter without breaking the line at the end.
Interesting challenge. I never bothered to draw a tree, always delegated to graphviz using language dot. Is this tree full or was it a coincidence of the example? Can I suggest trying not to center the parent node? , leaving it always to the left?
– Jefferson Quesado
If by full you mean that the children will always be sub-trees, no. It could be something like: (3 + (5 * 2)). Thus, one of the children of the "+" operation would only be 3. I believe that not centralizing the root of the tree would take away the purpose of drawing it. I have an HTML-based impression, which goes nesting tags within tags. But I’m not happy with it.
– NickD
Maybe this one reply no [so] can be useful in something.
– Woss
Has that other solution , that has a format very similar to that suggested by @Nickd
– Jefferson Quesado
The strategy that the Tree uses is distinct, but I believe it looks elegant, not to mention that it is apparently easy to implement
– Jefferson Quesado