Insert node in binary tree

1

How to insert a node into a binary tree? Always gives segmentation error when 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);
}
    
asked by anonymous 16.03.2017 / 23:55

1 answer

1

This code neither compiles, is disorganized, and has some flaws. I resolved by allocating initial memory for the tree, which caused the described error, and then there were some more confusions in the node allocation. There are still errors in the algorithm, but a step has already 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);
}

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

    
17.03.2017 / 01:35