1. 程式人生 > >二叉樹的插入和刪除

二叉樹的插入和刪除

#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;
}