There are several ways to implement the logic you want. The solution I show you is to invert the logic a little, so that show the first element normally, and each element of the front shows first the trace and then the number. This way it always comes out right and you don’t need to know the last element to "cancel the last dash".
How do you know which first element to print different ?
Well it also has several alternatives, a simple one is to pass the level of the element in which it is printing, and the root is the level 0
. At the level 0
prints only the number, and on the other levels prints first the trace to connect with the previous one, and then the number.
To maintain the function you have with the same prototype you need another auxiliary function that includes the level and increases it with each call.
Implementation of suggested logic:
void ImprimePreOrdemAux(TipoApontador arv, int nivel){
if(arv != NULL){
if (nivel != 0){ //so imprime o traço do anterior se não for o primeiro
printf("-");
}
printf("%d",arv->chave);
ImprimePreOrdemAux(arv->esq, nivel + 1);
ImprimePreOrdemAux(arv->dir, nivel + 1);
}
}
void ImprimePreOrdem(TipoApontador arv){
ImprimePreOrdemAux(arv, 0); //chama a função auxiliar com nivel 0
}
You can also implement the same without an auxiliary function and placing the nivel
as a global variable, but it is certainly an even simpler solution.
See an example of this implementation working on Ideone
Note also that this solution will work for any of the three ways of traversing the tree, the Infix, prefix or postfix.