Insert node into binary tree

Asked

Viewed 154 times

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.

1 answer

1


This code doesn’t even compile, is very disorganized and has some flaws. I decided to allocate initial memory to the tree, which caused the described error, and then there were some more confusions in the allocation of nodes. There are still errors in the algorithm, but a step has been taken.

#include <stdio.h>
#include <stdlib.h>

typedef struct no {
    int info;
    struct no *esq;
    struct no *dir;
} Node;

Node *insere(Node *arv, int valor) {
    if (arv == NULL) {
        arv = malloc(sizeof(Node));
        arv->info = valor;
        arv->esq = NULL;
        arv->dir = NULL;
        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 = malloc(sizeof(Node));
    arv->info = 1;
    arv->dir = NULL;
    arv->esq = NULL;
    insere(arv, 2);
    insere(arv, 3);
    imprime(arv);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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