Binary tree printing only left side

Asked

Viewed 103 times

1

Hello. My binary tree is printing only the left side, what can it be? I am using TAD to implement.

Tree structure:

typedef struct _no {
    int conteudo;
    struct _no *esquerda;
    struct _no *direita;
    struct _no *pai;
} Arvore;

Insertion function.

void inserir(Arvore **arv, int numero){
    Arvore *aux, *ant;
    aux = *arv;

    Arvore *novo;
    novo = (Arvore*) malloc(sizeof(Arvore));
    novo->direita = NULL;
    novo->esquerda = NULL;
    novo->conteudo = numero;

    if(estaVazia(*arv)){
        novo->pai = NULL;
        *arv = novo;
        return;
     }

    while (aux != NULL){
        ant = aux;

        if(numero > aux->conteudo){
            aux = aux->direita;
         }else{
            aux = aux->esquerda;
         }
     }

     if (numero > ant->conteudo){
        ant->direita = novo;
        novo->pai = aux;


     }else{
        ant->esquerda = novo;
        novo->pai = aux;

     }

     free(aux);
}

Printing function

void preOrdem(Arvore *arv){

    printf("%d ", arv->conteudo);
    preOrdem(arv->esquerda);
    preOrdem(arv->direita);


}

Main file

int main(){

    Arvore *arvore;

    inicializarArvore(&arvore);
    inserir(&arvore,20);
    inserir(&arvore,25);
    inserir(&arvore,10);
    inserir(&arvore,5);
    inserir(&arvore,30);

    preOrdem(arvore);

}

1 answer

3


Looking only at the function prints and assuming that the other functions are well implemented can repair that it does not give return in the function of printing.

void preOrdem(Arvore *arv){
    if(arv==NULL)
       return;

    printf("%d ", arv->conteudo);
    preOrdem(arv->esquerda);
    preOrdem(arv->direita);
}

inserir a descrição da imagem aqui

For its function it was in that node, when it is called again the function for the arv->esquerda goes to a null node and will close the program.

There needs to be the return for her to return to the number 7 and go to the direita

  • 1

    That’s right, thank you.

  • 1

    Recursiveness in trees is a complicated subject, it is necessary to know very well what does each thing. There are very good videos on youtube that teach step by step what makes each line of code.

Browser other questions tagged

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