69,336
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
node *lchild, *rchild;
}btree;
/*
查找函数:判断插入的数据是否已经存在(不能有重复的元素)
递归实现
*/
int search(btree *bt, int key)
{
if(!bt)
{
return 1;
}
else
{
if(bt->data == key)
{
printf("数据存在");
return 0;
}
if(bt->data > key)
{
search(bt->lchild, key);
}
if(bt->data < key)
{
search(bt->rchild, key);
}
}
return 1;
}
/*
插入函数:先查找看是否已经存在
小的数向左孩子走,大的数向右孩子走
*/
void insert(btree *bt, int key)
{
if(search(bt, key) == 1)
{
node *p = (node *)malloc(sizeof(node));
p->data = key;
p->lchild = p->rchild = NULL;
if(bt == NULL)
{
bt = p;
return;
}
node *temp = bt;//定义游标
while(temp)
{
if(key < temp->data)
{
temp = temp->lchild;
if(!temp)
{
temp->lchild = p;
}
}
else
{
temp = temp->rchild;
if(!temp)
{
temp->rchild = p;
}
}
}
}
}
void creat(btree *bt, int a[], int n)
{
int i;
for(i=0; i<n; i++)
{
insert(bt, a[i]);
}
}
void MidOrderTraverse(btree *bt)
{
node *p = bt;
if(p)
{
MidOrderTraverse(p->lchild);
printf("%d ", p->data);
MidOrderTraverse(p->rchild);
}
}
#include "BST.H"
void main()
{
btree bt;
int a[5] = {1, 3, 2, 4, 5};
creat(&bt, a, 5);
MidOrderTraverse(&bt);
}
while(temp)
{
if(key < temp->data)
{
temp = temp->lchild;
if(!temp)
{
temp->lchild = p;
}
}
else
{
temp = temp->rchild;
if(!temp) //问题出在这个地方,因为temp已经为NULL了,然后再操作temp->rchild = p;就会导致段错误;同理上面的操作
{
temp->rchild = p;
}
}
}
对NULL指针操作->rchild或->lchild都会导致段错误;建议重新梳理一下逻辑。void insert(btree **bt, int key)
{
if(search(*bt, key) == 1)
{
node *p = (node *)malloc(sizeof(node));
p->data = key;
p->lchild = p->rchild = NULL;
if(*bt == NULL)
{
*bt = p;
printf("helloworld\n");
return;
}
node *temp = *bt;//定义游标
while(temp)
{
if(key < temp->data)
{
temp = temp->lchild;
if(!temp)
{
temp->lchild = p;
}
}
else
{
temp = temp->rchild;
if(!temp->rchild)
{
temp->rchild = p;
}
}
}
}
}
void creat(btree **bt, int a[], int n)
{
int i;
*bt = NULL;
for(i=0; i<n; i++)
insert(bt, a[i]);
}
void MidOrderTraverse(btree *bt)
{
node *p = bt;
if(p)
{
MidOrderTraverse(p->lchild);
printf("%d ", p->data);
MidOrderTraverse(p->rchild);
}
}
//#include "BST.H"
//void main()
int main()
{
btree *bt = NULL;
int a[5] = {1, 3, 2, 4, 5};
creat(&bt, a, 5);
MidOrderTraverse(bt);
return 0;
}