二叉树的插入和删除

#include<stdio.h>
#include<stdlib.h>
int flag=1;//定义标签,用于show()只显示一次树的根结点
typedef struct tree
{
int data;
struct tree *lchild;
struct tree *rchild;

}treenode,*linktree;//树的结构体

linktree newnode(int data)
{
linktree new=malloc(sizeof(treenode));
if(new!=NULL)
{
new->data=data;
new->rchild=NULL;
new->lchild=NULL;
}
return new;


}//生成新结点

linktree insert(linktree root,linktree new)
{
//printf("in");
if(root==NULL)
{
printf("root NULL");
return new;
}
/*if(new==NULL)
printf("new NULL");
return NULL;
*/
if(new->data < root->data)
{
root->lchild=insert(root->lchild,new);//第归到最后将new插入到左结点,第归到最后返回new
//printf("l");
}
else
{
root->rchild=insert(root->rchild,new);
//printf("r");
}
//printf("in1");
return root;

}

linktree remove1(linktree root,int data)
{
if(root==NULL)
{
return NULL;
}
if(root->data > data)
{
root->lchild=remove1(root->lchild,data);
}
else if(root->data <data)
{
root->rchild=remove1(root->rchild,data);
}
//利用第归定位到要删除的数据的位置
else
{
//删除分三种情况,第一,有左结点,则将作结点的最右结点的数据替换要删除的结点的数据,并第归删除最右结点。
//有右结点,和左结点相似。
//没有结点,直接free掉
linktree tmp;
if(root->lchild != NULL)
{
for(tmp=root->lchild;tmp->rchild!=NULL;tmp=tmp->rchild);
root->data=tmp->data;
root->lchild=remove1(root->lchild,tmp->data);
}
else if(root->rchild != NULL)
{
for(tmp=root->rchild;tmp->lchild!=NULL;tmp=tmp->lchild);
root->data=tmp->data;
root->rchild=remove1(root->rchild,tmp->data);
}
else
{
free(root);
return NULL;
}
}

return root;

}
void show(linktree root)
{

//printf("show");
if(flag==1)
{
printf("%d",root->data);
flag=2;
}

//printf("%d",root->data);
if(root->rchild!=NULL)
{
printf("%d",root->rchild->data);
show(root->rchild);
}

if(root->lchild!=NULL)
{
printf("%d",root->lchild->data);
show(root->lchild);
}




}
int main()
{

int n,j,k;
linktree root=NULL;
scanf("%d",&j);
for(k=0;k<j;k++)
{
scanf("%d",&n);
if(n>0)
{
linktree new=newnode(n);
root=insert(root,new);
//printf("after inste ");
printf("\n");
}
if(n<0)
{
root=remove1(root,-n);
printf("%d is remove",-n);
}

}
show(root);

return 0;
}

转载于:https://www.cnblogs.com/zwjj/p/9816905.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值