求助:二叉树删除问题请指教
#include <stdio.h>#include <stdlib.h>
typedef struct node
{
int num;
struct node *left;
struct node *right;
}Node;
/*显示*/
/*中序遍历*/
void show(Node *ptr)
{
if(ptr!=NULL)
{
show(ptr->left);
printf("[%d]",ptr->num);
show(ptr->right);
}
}
/*创建二叉树*/
Node *sll_insert(Node *head,int value)
{
register Node *ptr;
register Node *back;
register Node *new_node;
/*创建新内存*/
new_node=(Node *)malloc(sizeof(Node));
if(!new_node)
{
fprintf(stderr,"ERROR");
exit(1);
}
new_node->num=value;
new_node->left=NULL;
new_node->right=NULL;
/*树为空,返回新结点*/
if(!head)
{
return new_node;
}
else
ptr=head;
while(ptr!=NULL)
{
back=ptr;
/*比较元素值与节点值*/
if(ptr->num<value)
{
ptr=ptr->right;/*节点大于元素值在右边*/
}
else
{
ptr=ptr->left;/*否则在左边*/
}
}
if(back->num>value)
{
back->left=new_node;
}
else
{
back->right=new_node;
}
return head;
}
/*查找涵数*/
Node *find_node(Node *head,int find_num,int *ops)
{
register Node *previous;
register Node *ptr;
previous=ptr;
ptr=head;
*ops=0;
while(ptr!=NULL)
{
if(ptr->num==find_num)
{
return previous;
}
else
previous=ptr;
if(ptr->num>find_num)
{
ptr=ptr->left;
*ops=-1;/*在左边*/
}
else
{
ptr=ptr->right;/*在右边*/
*ops=1;
}
}
return NULL;/*没有找到*/
}
/*删除*/
Node *del_delete(Node *head,int value)
{
register Node *ptr;
register Node *previous;
register Node *next;
int ops;
previous=find_node(head,value,&ops);
if(!previous)
return head;
switch(ops)
{
case 1:ptr=previous->right;break;/*在右边*/
case -1:ptr=previous->left;break;
case 0:ptr=previous;break;
}
if(ptr->left==NULL)/*没有左子树*/
{
if(ptr!=previous)/*是否结点*/
{
previous->right=ptr->right;
}
else
head=head->right;
free(ptr); return head;
}
if(ptr->right==NULL)/*没有右子树立*/
{
if(ptr->right==NULL)
{
previous->left=ptr->left;
}
else
head=head->left;
free(ptr);
return head;
}
/*有左子树,右子树结点*/
previous=ptr;/*保存父结点*/
next=ptr->left;
while(next->right!=NULL)
{
previous=next;
next=next->right;
}
ptr->num=next->num;
if(previous->left==next)
{
previous->left=next->left;
}
else
{
previous->right=next->right;
}
free(next);
return head;
}
/*主函数*/
int main()
{
register Node *head=NULL;
int num;
int del_num;
printf("输入值=>");
while(1)
{
scanf("%d",&num);
if(num==0)
{
break;
}
head=sll_insert(head,num);
show(head);
printf("\n");
}
printf("输入删除值==>");
while(1)
{
scanf("%d",&del_num);
if(del_num==0)
{
break;
}
head=del_delete(head,del_num);
show(head);
printf("\n");
}
return 0;
}
插入程序不能输入两个1。是什么问题?
删除不了整个树?请教一下前辈。