我正在尝试在 C 中递归地创建一个树。
到目前为止,我已经完成了下面的代码。但是在编译时我得到以下错误提示;
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); ^
我做错了什么?
#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);
}
}
谢谢。
最佳答案
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);
}
}
这应该可以解决您的问题:
你想递归地做它,所以你不需要 while 循环。
你想 malloc 结构的大小而不是指针的大小,并将它写入 main 中原始 p
的位置。
MakeTree 中的p
是指向struct 的指针,所以你必须解引用两次然后你想要成员的地址=> &(*p)->left
和 &(*p)->right
。
一个建议:不要调用结构 nohh 和指向它的指针 noh,那是不可读的。
关于递归创建树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26507312/