#include<stdio.h>
#include<stdlib.h>
struct bt{
struct bt *left;
int data;
struct bt *right;
};
struct bt *root,*p1 = NULL;
struct bt* create_bt(struct bt*);
main(){
p1 = create_bt(root);
printf("Binary tree created\n");
}
struct bt* create_bt(struct bt *root){
int a;
printf("Enter data:");
scanf("%d",&a);
if(a == -1){
root = NULL;
}
else{
root = (struct bt*)malloc(sizeof(struct bt));
root -> data = a;
root -> left = create_bt(root -> left);
root -> right = create_bt(root -> right);
printf("%d\n",root -> data);
p1 = root;
}
return p1;
}
最佳答案
声明:
else 部分中的 p1 = root;
应该位于 else 语句之外,以便如果 a==-1
则返回 NULL 并且左/右子元素被标记为无效的。
除此之外,您的代码在构建二叉树时似乎是正确的。
希望这会有所帮助。
关于c - 我想使用递归创建二叉树。我的以下代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34496101/