我寫了下面的代碼來創建二叉搜索樹,但是當創建函數被調用並且它試圖在程序第一次調用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