How to insert a Binary Search Tree in C

Asked

Viewed 40 times

-1

I’m not getting the insertion recursively and I don’t know what I’m doing wrong..

Precise follow the following prototypes:

struct Arvore {
    int info;
    struct Arvore *esq, *dir;
};
typedef struct Arvore Arvore;


void inserir(Arvore* a, int info);

I’m trying to do it this way:

void inserir(Arvore *a, int info) {
    if (a == NULL) {
        a = (Arvore *) malloc(sizeof(Arvore));
        a->info = info;
        a->esq = NULL;
        a->dir = NULL;
    } else if (info < a->info) {
        inserir(a->esq, info);
    } else {
        inserir(a->dir, info);
    }
}

But it doesn’t work, does anyone know how I can solve it? I’ve done a lot of research and I can’t find examples the way I need to implement them. (With the function prototype being void)

  • The way it is there, besides not working, you have a beautiful memory leak, since you don’t keep any reference to the allocated memory. As you said the return of the function should be void, an alternative would be to pass a pointer to pointer, setting the function as follows: void inserir(Arvore ** a, int info). And then it would be necessary to adapt the body of function.

  • post a complete code :(

1 answer

0

Maybe you’ll find it easier to read if you write like this:

#include <stdio.h>

typedef struct st_arv
{
    int info;
    struct st_arv*      esq;
    struct st_arv*      dir;

}   Arvore;

void inserir(Arvore*,int);

int         main(void)
{
    Arvore* A = NULL;
    Arvore  outra = { 1, NULL, NULL };
    return 0;
};

This prototype is not very happy. How to create a first node in a tree using inserir() like this? The pointer will not return.

Browser other questions tagged

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