二进制搜索树插入 – root始终为null
我有ds代码用于使用递归在二叉搜索树中插入值。 问题是root始终保持为null。 执行时,第一个printf()打印10,但第二个printf(在insertRec(10)之后)不打印任何内容,因为root为null。
#include #include 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 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(); }
您将root
作为值传递,因此对insert函数中的root
所做的更改不会反映在main函数中,因此root
函数在main函数中保持为NULL。 要纠正您的代码,您需要将指针传递给指针 。 传递root
地址以反映主要function的变化。
void insertRec(node *r, int num)
应编码如下:
void insertRec(node **r, int num) { if(*r==NULL) { *r= malloc(sizeof(node)); (*r)->data=num; //
并在插入函数中使用*root
。
并将其命名为insertRec(&root, 10);
来自主要。
此外,如果您动态分配内存,那么您应该使用free显式释放已分配的内存。
学习缩进C程序还有一件事。