typedef struct binary_tree_
{
int data;
struct binary_tree_ *left;
struct binary_tree_ *right;
}binary_tree; //这里binary_tree = struct binary_tree_
binary_tree* create_tree(int data) //创建一个根节点
{
binary_tree* root=NULL;
root=(binary_tree*)malloc(sizeof(struct binary_tree_));
root->data=data;
return root;
}
binary_tree* insert(int data,binary_tree *T)
{
if(T==NULL)
{
T=(binary_tree*)malloc(sizeof(struct binary_tree_));
T->data=data;
T->left=NULL;
T->right=NULL;
}
else if(data<T->data)
T->left=insert(data,T->left);
else if(data>T->data)
T->right=insert(data,T->right);
return T;
}
int main(void)
{
binary_tree *root;
binary_tree *root1;
root=create_tree(3);
root1=insert(2,root);
printf("%d",root1->data);
}
这是我自己写的关于二叉查找树的插入代码。求解大神为什么我一运行就崩溃。。。
创建根节点时出错,没有为左右节点赋初值,导致在插入时无法申请空间,程序崩溃
binary_tree* create_tree(int data)
{
binary_tree* root=NULL;
root=(binary_tree*)malloc(sizeof(struct binary_tree_));
root->data=data;
//加上下面两行
root->left=NULL;
root->right=NULL;
return root;
}
binary_tree* insert(int data,binary_tree *T)
这里你初始化T是不会作用到实参上去的,也就是说如果主程序T为null,调用你的函数,你的函数修改T分配空间,主程序的T还是null,应该用双重指针