1
How to insert a node into a binary tree? It always gives segmentation error when the code enters if (arv == NULL)
struct no {
int info;
struct no *esq;
struct no *dir;
};
typedef struct no node;
struct node *insere (node *arv, int valor) {
if (arv == NULL) { //aqui esta o erro
node p = malloc(sizeof(node));
p.info = valor;
p.esq = NULL;
p.dir = NULL;
*arv = p;
return arv;
}
else if (valor > arv->info) {
arv->dir = insere(arv->dir, valor);
return arv->dir;
}
else {
arv->esq = insere(arv->esq, valor);
return arv->esq;
}
void imprime (node *arv) {
if (arv != NULL) {
imprime(arv->esq);
printf("\n %d", arv->info);
imprime(arv->dir);
}
}
int main (void) {
node *arv;
arv->info = 1;
arv->dir = NULL;
arv->esq = NULL;
insere(arv, 2);
insere(arv, 3);
imprime(arv);
}
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.
– Maniero