二叉搜索树插入 - 根总是空 [英] Binary search tree insertion - root always null
问题描述
我有DS code使用递归的二叉搜索树插入值。的问题是,根始终保持为空。
在执行时,第一次的printf()打印10,但第二次的printf(后insertRec(10))以root为空不打印任何东西。
#包括LT&;&stdio.h中GT;
#包括LT&;&malloc.h所GT;结构LLIST
{
int数据;
结构LLIST *离开;
结构LLIST *权利;
};
typedef结构LLIST节点;无效insertRec(节点* R,INT NUM)
{
如果(R == NULL)
{
R =(节点*)malloc的(的sizeof(节点));
R->数据= NUM;
R->左= NULL;
R->右= NULL;的printf(%D,R 34 GT;数据); // 1日的printf }
其他
{
如果(NUM< R->数据)
insertRec(R 34 GT;左,NUM);
其他
insertRec(R 34 GT;右,NUM);
}
}
无效显示(节点* X)
{
如果(X!= NULL)
{
显示(X-GT&;左);
的printf(%d个 - >中,X轴和GT;数据);
显示(X-GT&右);
}
其他
返回;
}
诠释的main()
{
节点*根= NULL;
insertRec(根,10);
如果(根!= NULL)
的printf(\\ n数据=%d个根 - >数据); //第二的printf
insertRec(根,5);
insertRec(根,15);
insertRec(根,3);
insertRec(根,18);
显示器(根);
残培();
}
您逝去的根
的值,从而为根所做的更改
在插入函数并不反映的主要功能,因此根
仍是主要功能为NULL。要纠正你的code,你需要传递指针的指针。通过根
的地址,以反映主要功能的变化。
无效insertRec(节点* R,INT NUM)
应该是codeD这样的:
无效insertRec(节点** R,INT NUM)
{
如果(* R == NULL)
{
* R =的malloc(sizeof运算(节点));
(* R) - GT;数据= NUM; //
和使用 *根
插入函数内。
和称呼其为 insertRec(安培;根,10);
从主。
此外,如果您分配内存动态,那么你应该使用无显式释放分配的内存。
还有一件事学习缩进C程序。
I have ds code for inserting values in a binary search tree using recursion. The problem is that the root always remains null. Upon execution, the 1st printf() prints 10 but the 2nd printf (after insertRec(10)) does not print anything as root is null.
#include<stdio.h>
#include<malloc.h>
struct llist
{
int data;
struct llist *left;
struct llist *right;
};
typedef struct llist node;
void insertRec(node *r, int num)
{
if(r==NULL)
{
r=(node*)malloc(sizeof(node));
r->data=num;
r->left=NULL;
r->right=NULL; printf("%d ",r->data); //1st printf
}
else
{
if(num < r->data)
insertRec(r->left, num);
else
insertRec(r->right, num);
}
}
void display(node *x)
{
if(x != NULL)
{
display(x->left);
printf("%d-->",x->data);
display(x->right);
}
else
return;
}
int main()
{
node *root=NULL;
insertRec(root,10);
if(root !=NULL)
printf("\ndata=%d",root->data); //2nd printf
insertRec(root,5);
insertRec(root,15);
insertRec(root,3);
insertRec(root,18);
display(root);
getch();
}
You are passing root
as value so changes made to root
in insert function doesn't reflect at main function, hence root
remains NULL in main function. To rectify your code, you need to pass Pointer to pointer. Pass address of root
to reflect change in main function.
void insertRec(node *r, int num)
should be coded like:
void insertRec(node **r, int num)
{
if(*r==NULL)
{
*r= malloc(sizeof(node));
(*r)->data=num;
//
and use *root
inside insert function.
And call it as insertRec(&root, 10);
from main.
Additionally, if you allocates memory dynamically then you should free allocated memory using free explicitly.
One more thing learn Indenting C Programs.
这篇关于二叉搜索树插入 - 根总是空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!