I am suffering from the following problem: I want to print the "drawing" of a tree in the terminal.
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 tree root is the operation and the children are the values.
I can print them in a line, it would look 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 something like:
|-|
|
|+|-----------|*|
| |
|2|-----|5| |3|-----|1|
The structure of my stack 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 here is my attempt to print:
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 handle the spacing.
PS: Top is a reference to the top of the stack. In case, it would be a Node.
PS2: At first only binary trees are generated, but in the future I would like to add methods that simplify accounts and make the tree generic.
PS3 .: The addChar method simply adds the character passed as a parameter, without breaking the line at the end.