[英]Difficulties implementing a binary search tree in C
我已经尝试在C中实现一个二进制搜索树几个小时了,并且我将主要问题缩小到插入函数,您将在下面看到。 出现的问题是,当我将root设置为null,然后尝试插入时,它一遍又一遍地创建根节点,但是没有任何变化(我多次收到“形成根节点消息”,遍历不起作用)。 但是,当我取消注释行//root = newNode(3,NULL,NULL);
,并手动创建根节点,所有插入操作均正常,顺序遍历也正常。 我希望能够在函数中创建根节点,而不是像这样手动创建。 一段时间以来,这一直让我感到沮丧,因此,不胜感激。 谢谢!
#include <stdio.h>
#include <stdlib.h>
struct node {
int key;
struct node* left;
struct node* right;
};
struct node* newNode(int val, struct node* lchild, struct node* rchild) {
struct node* temp = malloc(sizeof(struct node));
if(temp == NULL) { printf("Error creating node! Exiting."); exit(1); }
temp->key = val;
temp->left = lchild;
temp->right = rchild;
return(temp);
}
void add(int val, struct node* current) {
if (current == NULL) {
printf("forming root node\n");
current = newNode(val,NULL,NULL);
} else if (val <= current->key) {
if (current->left == NULL) {
current->left = newNode(val, NULL, NULL);
} else {
add(val, current->left);
}
} else {
if (current->right == NULL) {
current->right = newNode(val, NULL, NULL);
} else {
add(val, current->right);
}
}
}
void inOrder(struct node* current) {
if (current != NULL) {
inOrder(current->left);
printf("%d ", current->key);
inOrder(current->right);
}
}
int main() {
struct node* root = NULL;
//root = newNode(3,NULL,NULL);
add(3, root);
add(2, root);
add(4, root);
add(16, root);
inOrder(root);
}
C仅是按值传递。 如果要从函数返回数据,则必须将指针传递到要修改的数据,或者返回它。 您的add()
-函数当前不执行任何操作。
我的建议是,使用返回值。
可能的更正原型:
struct node* add(int val, struct node* current)
void add(int val, struct node** current)
这是因为您要按值传递根节点的值。 在main()中,创建一个节点*(根)并将其设置为NULL。 这意味着root的内存地址为0。问题是不返回任何值,因此无论您在add()中执行什么操作,root的值都将保持NULL或0。当您手动创建根节点时,它将之所以起作用,是因为add()可以在给定的地址处修改内存,并且root的值有意义,因此这些更改会持续存在,但是当root为null时,add()所做的所有更改都会丢失。
您要修改 current
指针,将指针传递给它。
void add(int val, struct node **ptree);
{
if(*ptree == NULL) {
struct node *tmp = malloc(sizeof(*tmp));
tmp->val = val; tmp->left = tmp->right = NULL;
*ptree = tmp;
}
else if (val == (*ptree)->val)
/* Scream about duplicate insertion */
else if (val < (*ptree)->val)
add(val, &((*ptree)->left));
else /* val > (*ptree)->val */
add(val, &((*ptree)->right));
}
被称为例如add(42, &tree);
如果tree
是(将)指向根的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.