- 注册时间
- 2004-10-13
- 最后登录
- 2019-5-15
⑧专业
*永恒国度*
- 积分
- 14145

|
程序如下:- #include<stdio.h>
- #include<stdlib.h>
- #define MaxSize 100
- #define MaxWidth 40
- typedef struct node
- {
- char data;
- struct node *left,*right;
- }BTree;
- BTree *creatree(char str[],int n)
- {
- int i;
- BTree *BT=NULL,*p,*s;
- for(i=0;i<n;i++)
- {
- s=(BTree *)malloc(sizeof(BTree));
- s->data=str[i];s->left=s->right=NULL;
- p=BT;
- if(p==NULL)
- BT=s;
- else
- {
- while(p->left!=s && p->right!=s)
- {
- if(s->data < p->data)
- {
- if(p->left!=NULL)
- p=p->left;
- else
- p->left=s;
- }
- else
- {
- if(p->right!=NULL)
- p=p->right;
- else
- p->right=s;
- }
- }
- }
- }
- return(BT);
- }
- BTree *find(BTree *BT,int x) //寻找元素
- {
- BTree *p=BT;
- while(p!=NULL && p->data!=x)
- {
- if(x<p->data)
- p=p->left;
- else
- p=p->right;
- }
- return p;
- }
- void del(BTree **BT,int x)
- {
- BTree *p=*BT,*q,*r,*t;
- q=NULL;
- while(p!=NULL && p->data!=x)
- if(x < p->data)
- {
- q=p;
- p=p->left;
- }
- else
- {
- q=p;p=p->right;
- }
- if(p==NULL)
- printf("未发现数据为%d的结点\n",x);
- else if(p->left==NULL) //删除点无左子树
- {
- if(q==NULL) //删除点是根结点
- t=p->right;
- else if(q->left==p)
- q->left=p->right;
- else
- q->right=p->right;
- }
- else
- {
- r=p->left;
- while(r->right!=NULL)
- r=r->right;
- r->right=p->right;
- if(q==NULL) t=p->left; //删除点是根结点
- else if(q->left==p) q->left=p->left;
- else q->right=p->left;
- }
- }
- void disptree(BTree *BT) //前序法显示二叉树
- {
- BTree *stack[MaxSize],*p;
- int level[MaxSize][2],top,n,i,width=4;
- if(BT!=NULL)
- {
- printf("\n凹入表示法:\n");
- top=1;
- stack[top]=BT;
- level[top][0]=width;
- while(top>0)
- {
- p=stack[top];
- n=level[top][0];
- for(i=1;i<=n;i++)
- printf(" ");
- printf("%c",p->data);
- for(i=n+1;i<=MaxWidth;i+=2)
- printf("-");
- printf("\n");
- top--;
- if(p->right!=NULL)
- {
- top++;
- stack[top]=p->right;
- level[top][0]=n+width;
- level[top][1]=2;
- }
- if(p->left!=NULL)
- {
- top++;
- stack[top]=p->left;
- level[top][0]=n+width;
- level[top][1]=1;
- }
- }
- }
- }
- void main()
- {
- BTree *B,*p;
- char str[]={'4','5','2','1','6','9','3','8'};
- printf("初始化二叉树:");
- B=creatree(str,8);
- disptree(B);
- p=find(B,'1');
- if(p==NULL) printf("值域为1的结点未找到!\n");
- else printf("值域为1的结点存在!\n");
- del(&B,'4');
- disptree(B);
- }
复制代码
删除的过程是:先找到要删除的结点, 如果删除点没有左子树,则用右子树代替被删点, 如果删除点有左子树则在其左子树中找到最右结点来代替被删的结点.(即将那最右的结点的右指针置成删除点所指结点的右子树的根,然后用删除点的左子树的根结点代替被删除点所指的结点.)
在这一句del(&B,'4'); 删除的是根结点(最顶那个结点)的时候,结果怎么那么奇怪呢?好像对,又好像不对,
还有它判断是否根结点的这一句 if(q==NULL) t=p->left; t 好像只是接收p的left 但并没有改变 树原来的结构啊? 到底应该怎么去理解呢??? |
|