Recursive function of Insert nodes

0

Looking at other problems, I realized the need to use pointers in certain tree functions. So I defined the Insert function as:

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

The problem is that later, at the time of 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'll leave the code a bit more complete, for better insight (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);

}
    
asked by anonymous 25.08.2017 / 18:04

1 answer

0

It is as follows, its function insertsNo parameter is an address of a pointer, and an integer. Therefore in insereNo((*A)->esq, chave) and insereNo((*A)->dir, chave should be insereNo(&((*A)->esq), chave) and insereNo(&((*A)->dir), chave) .

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

In addition, you are doing return (*A) at the end of your insereNo function, this will give segmentation fault. The correct would be return novo .

    
26.08.2017 / 03:21