Recursive function of Insert Nodes

Asked

Viewed 453 times

0

Analyzing other problems, I realized the need to use pointers on certain tree functions. So I set the Insert function to :

Arvore* insereNo (Arvore** A, int chave)

The point is that later, when inserting new nodes, there is a problem regarding the function call :

if (chave < (*A)->chave){
  (*A)->esq = insereNo((*A)->esq, chave);
}

else {
  (*A)->dir = insereNo((*A)->dir, chave);
}

How to proceed with the pointers ? I will make the code a little more complete, for better perception (remembering that this is a sketch for red-black tree).

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

#define PRETO 1
#define VERMELHO 0

struct No {

  int cor;
  int chave;
  struct No* esq, *dir;
  struct No* pai;

} No;

typedef struct No Arvore;

////////////////////////////////////////////////////////////

Arvore* insereNo (Arvore** A, int chave){

  struct No* novo = (struct No*)malloc(sizeof(struct No));

  if (novo == NULL){
      return NULL;
  }

  novo->chave = chave;
  novo->esq = NULL;
  novo->dir = NULL;
  novo->cor = VERMELHO;

  if ( *A == NULL){
      *A = novo;
      return *A;
  }

  if ( chave == (*A)->chave){
      free(novo);
      return NULL;
  }

  else {

      if (chave < (*A)->chave){
          (*A)->esq = insereNo((*A)->esq, chave);
      }

      else {
          (*A)->dir = insereNo((*A)->dir, chave);
      }
  }

  return (*A);
}

//////////////////////////////////////////////////////


int main(){

  Arvore* A = NULL;

  insereNo(&A, 10);
  insereNo(&A, 11);

}

1 answer

0


It is the following, its function inserts No takes as parameter an address of a pointer, and an integer. So in insereNo((*A)->esq, chave) and insereNo((*A)->dir, chave should be insereNo(&((*A)->esq), chave) and insereNo(&((*A)->dir), chave).

And remember that your function insereNo returns a pointer, so in its main function it must be A = insereNo(&A, 10); and A = insereNo(&A, 11);

Besides, you are doing return (*A) at the end of its function insereNo, this will give Segmentation fault. The correct would be return novo.

Browser other questions tagged

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