程序出现死循环啦,各位帮忙呀,帮我改正确吧,我无奈了
#include<stdio.h>#include<malloc.h>
typedef struct treenode
{
int key;
treenode *lch;
treenode *rch;
}treenode,*tree;
void creat(tree &T)//建树
{
int ch;
int n=0;
printf("输入结点的值:");
scanf("%d",&ch);
if(ch==0)
T=NULL;
else
{
T=(treenode*)malloc(sizeof(treenode));
T->key=ch;
n=n+1;
if(n==1)
root=T;
printf("%d",T->key);
printf("左孩子");
creat(T->lch);
printf("%d",T->key);
printf("右孩子");
creat(T->rch);
}
}
void visit(treenode *q)//输出结点值
{
printf("输出结点值:");
printf("%d\n",q->key);
}
treenode *Parent(tree T,tree x)
{
if(T==NULL)
return NULL;
else if((T->lch==x)||(T->rch==x))
{
return T;
if(T->lch!=NULL)
Parent(T->lch,x);
if(T->rch!=NULL)
Parent(T->rch,x);
}
else
{
printf("No Found");
return NULL;
}
}
int preodertraverse(tree T,void visit(treenode *q))//先序遍历二叉树
{
while(T)
{
visit(T);
preodertraverse(T->lch,visit);
preodertraverse(T->rch,visit);
}
return 0;
}
int Inordertraverse(tree T,void visit(treenode *q))//中序遍历二叉树,采用非递归
{
while(T)
{
Inordertraverse(T->lch,visit);
Inordertraverse(T,visit);
Inordertraverse(T->rch,visit);
}
return 0;
}
void Aodertraverse(tree T)//后序遍历
{
while(T)
{
if(T->lch)
Aodertraverse(T->lch);
Aodertraverse(T->rch);
visit(T);
}
}
treenode *serch(tree T,int k)//查找结点值为K的结点
{
tree r;
r=T;
if(T==NULL)
return NULL;
else
{
if(r->key=k)
return r;
else
if(r->key>k)
return serch(r->lch,k);
else
return serch(r->rch,k);
}
}
treenode* deletetreenode(tree T,int n2)//删除值为n2的结点
{
tree r2,r3;//r3为r2的父结点
if(T==NULL)
printf("空树");
else
r2=serch(T,n2);
r3=Parent(T,r2);
if(!r2->lch&&!r2->rch)//r2为叶子结点
{
if(r3->lch=r2)//r2为r3的左孩子
r3->lch=NULL;
else
r3->rch=NULL;
}
else
{
if(r2->lch)//左或者右子树为空
{
r3->lch=r2;
r3->lch=r2->lch;
}
else
{
r3->rch=r2;
r3->lch=r2->rch;
}
}
if(r2->lch&&r2->rch)//先序遍历连结结点
{
r3->lch=r2;
r3->lch=r2->lch;
r3->lch->lch=r2->rch;
}
else
{
r3->rch=r2;
r3->rch=r2->lch;
r3->lch->lch=r2->rch;
}
return T;
}
int main()
{
tree T;
int n2;
T=creat(T);
printf("进行后序遍历");
Aodertraverse(T);
printf("进行先序遍历");
preodertraverse(T,visit);
printf("进行中序遍历");
Inordertraverse(T,visit);
printf("输入要删除的数:");
scanf("%d",&n2);
deletetreenode(T,n2);
return 0;
}