Kaiser
Kaiser

Reputation: 35

Creating a Tree recursively

I'm trying to create a Tree recursively in C.

So far I have done the code below. But when compiling I get the following error massages;

error: request for member ‘esq’ in something not a structure or union MakeTree(H-1, p->left, p); ^ error: request for member ‘dir’ in something not a structure or union MakeTree(H-1, p->right, p); ^

What am I doing wrong?

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

typedef struct nohh {
  int info;
  struct nohh *left;
  struct nohh *right;
  struct nohh *up;
} nohh, *noh;

void MakeTree(int H, noh *p, noh *u);

int main(){
  noh p = NULL;
  int h;

  printf("What is the Tree height? ");
  scanf("%d\n", &h);

  MakeTree(h, &p, &p);

  return 0;
}

void MakeTree(int H, noh *p, noh *u){

  while(H>=0){
    p = malloc(sizeof(noh));
    (*p)->up = *u;
    MakeTree(H-1, p->left, p);
    MakeTree(H-1, p->right, p);
  }
}

Thanks.

Upvotes: 0

Views: 96

Answers (2)

Jabberwocky
Jabberwocky

Reputation: 50775

This solution is somewhat more readable avoiding pointers to pointers.

struct nohh {
  int info;
  struct nohh *left;
  struct nohh *right;
  struct nohh *up;
} ;

struct nohh *MakeTree(int h, struct nohh *up)
{
  if (h >= 0)
  {
    struct nohh *p = (struct nohh *)malloc(sizeof(struct nohh));
    p->up = up;
    p->left  = MakeTree(h - 1, p);
    p->right = MakeTree(h - 1, p);
    return p ;
  }

  return NULL ;
}


int main(){
  struct nohh *p ;
  int h;

  printf("What is the Tree height? ");
  scanf("%d", &h);

  p = MakeTree(h, NULL);

  return 0;
}

Upvotes: 1

mch
mch

Reputation: 9804

void MakeTree(int H, noh *p, noh *u)
{
  if (H>0)
  {
    *p = malloc(sizeof(nohh));
    (*p)->up = *u;
    MakeTree(H-1, &(*p)->left, p);
    MakeTree(H-1, &(*p)->right, p);
  }
}

this should fix your problems:

you want to do it recursive, so you don't need the while loop. you want to malloc the size of the struct and not of the pointer and write it to the place of the original p in main. p in MakeTree is a pointer to pointer to struct, so you have to dereference twice and then you want the address of the member => &(*p)->left and &(*p)->right.

a suggestion: don't call a struct nohh and the pointer to it noh, that's not readable.

Upvotes: 2

Related Questions