【发布时间】:2018-06-19 19:25:24
【问题描述】:
我已经做了一个二叉搜索树
struct BTNode
{
int info;
struct BTNode *left,*right;
};
我写了一个代码来在树中插入一个节点
void insert(struct BTNode *root,int data)
{
struct BTNode *ptr;
struct BTNode *n=malloc(sizeof(struct BTNode));
n->info=data;
n->left=NULL;
n->right=NULL;
if(root==NULL)
root=n;
else{
ptr=root;
while(ptr!=NULL){
if(data<ptr->info){
if(ptr->left==NULL)
ptr->left=n;
else
ptr=ptr->left;
}
else if(data>ptr->info){
if(ptr->right==NULL)
ptr->right=n;
else
ptr=ptr->right;
}
}
}
}
还有一个 main() 函数
int main()
{
struct BTNode *root=NULL;
int choice,data;
printf("\n1.Insert 2.Preorder 3.Exit\n");
scanf("%d",&choice);
switch(choice){
case 1:
printf("\nWrite the data: ");
scanf("%d",data);
insert(root, data);
break;
但是当我尝试插入一个节点时,我的程序崩溃了。任何提示有什么问题?
【问题讨论】:
-
root=n;只会在函数中生效。 -
if(root==NULL) root=n;您只是将本地变量设置为指向n -
我只是好奇,你是用这样的格式编码还是因为堆栈溢出编辑器或其他原因?
标签: c pointers tree malloc binary-search-tree