我想使用递归创建一个二叉树。我的以下代码有什么问题?
I want to create a binary tree using recursion. What is wrong in my following code?
#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
那么它 returns NULL 并且 left/right child 被标记为 NULL。
除此之外,您的代码在构建二叉树时似乎是正确的。
希望这有帮助。
#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
那么它 returns NULL 并且 left/right child 被标记为 NULL。
除此之外,您的代码在构建二叉树时似乎是正确的。
希望这有帮助。