梦,才是最真的现实

导航

查找二叉树的基本操作以及层次遍历

#include<stdio.h>
#include<stdlib.h>
#define Max 100
typedef struct btree
{
int data;
struct btree *left;
struct btree *right;
}tree;
typedef struct Queue
{
int tail,head;
tree * a[Max];
}queue;
void create(queue &);
void enqueue(int k,queue&);
tree * dequeue(queue &);
int empty(queue );
void insert(int k,tree *&);
void order(tree *t);
int main()
{
int k,i,n;
void deletekey(int k,tree *&t);
tree *t;
printf("你想输入多少个元素?\n");
scanf("%d",&n);
t=NULL;
for(i=0;i<n;i++)
{
scanf("%d",&k);
insert(k,t);
}
    printf("输入结果如下:\n");
order(t);
printf("输入你想删除的数值:\n");
scanf("%d",&k);
deletekey(k,t);
printf("删除后的二叉树如下:\n");
order(t);
return 0;
}
void deletekey(int k,tree *&t)
{
void find(int ,tree *&,tree *&,tree *t,int &);
int found=0;
tree *p,*pfather,*q,*qfather;
find(k,p,pfather,t,found);
if(found)
{
if(p->left==NULL)
q=p->right;
else
{
q=p->left;
if(q->right==NULL)
{
q->right=p->right;
}
else
{
do
{
qfather=q;
q=q->right;
}while(q->right);
qfather->right=q->left;
q->left=p->left;
q->right=p->right;
}
}
if(p==t)
{
t=q;
}
else 
if(pfather->left==p)  pfather->left=q;
else pfather->right=q;
free(p);
}
else printf("FAILED!\n");
}
void find(int k,tree *&p,tree *&pfather,tree *t,int &found)
{
p=t;
pfather=NULL;
while(t&&!found)
{
if(p->data==k)
{
found=1;
return ;
}
pfather=p;
if(k>p->data)
p=p->right;
if(k<t->data)
p=p->left;
}
}
void create(queue& q)
{
q.head=q.tail=0;
}
void enqueue(tree * k,queue&q)
{
if((q.tail+1)%Max==q.head)
{
printf("OVER FLOW!\n");
return ;
}
q.a[q.tail]=k;
q.tail=(q.tail+1)%Max;
}
tree* dequeue(queue &q)
{
tree *k;
if(q.head==q.tail)
{
printf("UNDER FLOW!\n");
return NULL;
}
k=q.a[q.head];
q.head=(q.head+1)%Max;
return k;
}
int empty(queue q)
{
if(q.head==q.tail)  return 1;
else return 0;
}
void order(tree *t)
{
queue q;
create(q);
if(t==NULL)
{
printf("NO!\n");
return;
}
enqueue(t,q);
while(!empty(q))
{
t=dequeue(q);
printf("%d ",t->data);
if(t->left) enqueue(t->left,q);
if(t->right) enqueue(t->right,q);
}
putchar('\n');
}
void insert(int k,tree *&t)
{
tree *p,*pf,*pfather;
pf=t;
p=(tree *)malloc(sizeof(tree));
p->data=k;
p->left=p->right=NULL;
if(t==NULL)
{
t=p;
return ;
}
while(pf)
{
pfather=pf;
if(pf->data>k) pf=pf->left;
else pf=pf->right;
}
if(pfather->data>k)  pfather->left=p;
else pfather->right=p;
}

posted on 2012-04-30 01:16  梦,才是最真的现实  阅读(232)  评论(0编辑  收藏  举报