[英]Insert new node in a binary search tree at C
I already have a binary search tree with 5 levels, I am trying to create a function which inserts a new node but I can't do it working right. 我已经有一个具有5个级别的二进制搜索树,我试图创建一个插入新节点的函数,但无法正常工作。 How can I edit my code to do the insertion?
如何编辑代码以进行插入?
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;}
If this num > node->rec
is true you need to check whether node->rp
is NULL
or not, which you didn't check. 如果此
num > node->rec
为true,则需要检查node->rp
是否为NULL
未检查)。
Also pass the address of head
to insertion()
so that modification in passed variable head
affects in calling function and you no need to return anything. 还要将
head
的地址传递给insertion()
以便在传递的变量head
中进行修改会影响调用函数,并且您无需返回任何内容。
Assume you are calling insertion()
like below 假设您正在像下面那样调用
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;
}
And insertion()
function looks like 和
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;
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.