How to ignore the last element in recursive call

Asked

Viewed 44 times

1

I’m implementing a C tree, and one of my methods prints my tree in preorder, and separating the numbers with -.

I created that function:

void ImprimePreOrdem(TipoApontador arv){
    if(arv!=NULL){
        printf("%d-",arv->chave);
        ImprimePreOrdem(arv->esq);
        ImprimePreOrdem(arv->dir);
    }
}

However, for example if my tree contains the numbers from 1 to 10, when I print the tree elements recursively, the application - in the end, leaving the exit like this:

1-2-3-4-5-6-7-9-10-

How do I exclude the latter - of my leaving?

1 answer

3


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.