[英]Insertion failure in a Binary Search Tree
這是我用於創建和插入二進制搜索樹的代碼
struct BTNode
{
int info;
struct BTNode *left, *right;
};
struct BTNode* create(int data)
{
struct BTNode *root;
struct BTNode *n = malloc(sizeof(struct BTNode));
n->info = data;
n->left = NULL;
n->right = NULL;
root = n;
return(root);
}
struct BTNode* insert(struct BTNode *root, int data)
{
struct BTNode *ptr;
struct BTNode *n = malloc(sizeof(struct BTNode));
if (n == NULL)
printf("\nOUT OF MEMORY!\n");
n->info = data;
n->left = NULL;
n->right = NULL;
ptr = root;
while (ptr != NULL){
if (data < ptr->info){
if (ptr->left == NULL)
ptr->left = n;
ptr = ptr->left;
}
else if (data > ptr->info){
if (ptr->right == NULL)
ptr->right = n;
ptr = ptr->right;
}
}
return(n);
}
這是main()函數
int main()
{
struct BTNode *root = NULL;
int choice, data;
printf("\nWrite the root data: ");
scanf("%d", &data);
root = create(data);
while (1){
printf("\n1.Insert 2.Preorder 3.Exit\n");
scanf("%d", &choice);
switch(choice){
case 1:
printf("\nWrite the data: ");
scanf("%d", &data);
insert(root, data);
break;
我能夠創建根節點,但是每當我嘗試插入數據時,我都會給我數據,而編譯器將停止執行任何操作。 知道為什么會這樣嗎?
while()
循環將永遠持續下去,因為即使在找到插入節點的位置之后,您仍會繼續循環:
while(ptr!=NULL){
if(data<ptr->info){
if(ptr->left==NULL)
ptr->left=n;
ptr=ptr->left;
}
else if(data>ptr->info){
if(ptr->right==NULL)
ptr->right=n;
ptr=ptr->right;
}
}
插入節點后,您需要打破while()
循環:
while (ptr != NULL) {
if (data < ptr->info) {
if (ptr->left == NULL) {
ptr->left = n;
break;
}
ptr = ptr->left;
} else if (data > ptr->info) {
if (ptr->right == NULL) {
ptr->right = n;
break;
}
ptr = ptr->right;
}
}
另外,用於檢查malloc()
失敗的獎勵積分
struct BTNode *n = malloc(sizeof(struct BTNode));
if (n == NULL)
printf("\nOUT OF MEMORY!\n");
但是無論如何簡單地繼續運行,負點是,如果malloc()
失敗,則應該退出該函數
struct BTNode *n = malloc(sizeof(struct BTNode));
if (n == NULL) {
printf("\nOUT OF MEMORY!\n");
return NULL:
}
然后,當然,調用insert()
的代碼應該知道如果insert()
返回NULL時該怎么做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.