There are several ways you can implement the logic you want. The solution I show you is to reverse the logic a bit, so that you show the first element normally, and each element in the front first shows the trace and then the number. This way it always comes out right and you do not need to know the last element to "cancel the last trace".
How do you know which first element to print differently?
Well you also have several alternatives, a simple is to pass the level of the element you are printing, the root is the 0
level. At the 0
level prints only the number, and at the other levels prints the trace first to connect to 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 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 putting nivel
as a global variable, but it is certainly a worse solution even though it is simpler.
See an example of this implementation working on Ideone
Note also that this solution will work for any of the three ways to go through the tree, infix , prefix or postfix / p>