我已经有了一个包含5个级别的二叉搜索树,我正在尝试创建一个插入新节点但我无法正常工作的函数。如何编辑我的代码以进行插入?
TREE *insertion(TREE *root, int num){
TREE *node, *new_node;
node = root;
new_node=(TREE *)malloc(sizeof(TREE));
new_node->rec = num;
new_node->lp = NULL;
new_node->rp = NULL;
while(node != NULL ){
// if(node->rec == num){
// printf("This value exists\n");
// return NULL;
// }
if(num > node->rec){
node = node->rp;
}
else
node = node->lp;
}
if(num>node->rec)
node = new_node;
else
node = new_node;
return root;}
答案 0 :(得分:0)
如果num > node->rec
为真,您需要检查node->rp
是否为NULL
,而您未检查。
同时将head
的地址传递给insertion()
,以便传递的变量head
中的修改会影响调用函数,而您无需返回任何内容。< / p>
假设您正在调用insertion()
,如下所示
int main(void) {
TREE *head = NULL;
insertion(&head,10);/* pass the address of head so that modification will affect here also otherwise just passing head means it will treat as call by value */
insertion(&head,5);
insertion(&head,15);
return 0;
}
insertion()
函数看起来像
int insertion(TREE **root, int num) {
TREE *node, *new_node;
node = *root;
new_node = malloc(sizeof(TREE)); /* no need of casting malloc() results */
new_node->rec = num;
new_node->lp = NULL;
new_node->rp = NULL;
while(node != NULL ){
if(node->rec == num){
printf("This value exists\n");
return NULL;`
}
if(num > node->rec){ /* right child of root node */
if(node->rp != NULL) { /* check node->rp is empty or not
if not, update node.. check here itself */
node = node->rp; /* update node */
}
else {
node->rp = new_node; /* insert new node */
return; /* new node added at correct position , so no need of any further processing, jut return */
}
}
else {
if(node->lp != NULL) {
node = node->lp;
}
else {
node->lp = new_node;
return;
}
}
}
}