我写了下面的代码来创建二叉搜索树,但是当创建函数被调用并且它试图在程序第一次调用insertNode(...)挂了。以下是密码:C中的二叉搜索树程序行为奇怪
struct BstNode{
int value;
struct BstNode* left;
struct BstNode* right;
};
struct BstNode *root;
struct BstNode* insertNode(struct BstNode* root, int data){
if(data <= root->value)
root->left = insertNode(root->left, data);
else
root->right = insertNode(root->right, data);
printf("%d ",root->value);
return root;
}
void create(struct BstNode* root){
int data;
if(root == NULL){
//create the root node
printf("\nInside create");
root = (struct BstNode*) malloc(sizeof(struct BstNode));
printf("\nData :: ");
scanf("%d",&data);
root->value = data;
root->left = NULL;
root->right = NULL;
}
else{
printf("\nCalling insertNode()");
printf("\nData :: ");
scanf("%d",&data);
root = insertNode(root, data); // The program hangs up here : the very first time this line is executed
printf("\nCalled insert");
}
}
int main(){
root = NULL;
int i;
for(i=0;i<5;i++){
create(root);
printf("%d ",root->value); // For checking the value
}
return 0;
}
有人可以指出我的错误。任何建议都很有帮助。
首先你要通过值**传递根指针**,这将不会适当地设置它。您也不会随时设置数据变量。 – Nate
'create()'中的参数名称'root'会隐藏全局变量'root'。 – EOF
@EOF:我应该改变'create()'的返回类型并将其设置为'struct BstNode * create(struct BstNode * rootNode,int data){}'? – mustangDC