数据结构作业之二叉树和树的销毁

该博客围绕数据结构作业展开,主要内容是二叉树和树的销毁,属于信息技术领域中数据结构相关知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据结构作业,二叉树和树的销毁


#include <stdio.h>
#include <stdlib.h>
typedef struct snode
{
 char data;
 struct snode *lchild,*rchild;
}bitree,*biTree;
typedef struct node 
{
 char data;
 struct node *firstchild,*nextsibling;
}tree,*Tree;
typedef struct queue
{
 Tree *data;
 int rear;
 int first;
 int maxsize;
}squeue;
void createbitree(biTree &T);
void desttree(biTree T);
int initqueue(squeue *S);
int enqueue(squeue *S,Tree T);
Tree gettop(squeue S);
Tree dequeue(squeue *S);
void creatree(Tree &T);
void disptree(Tree T);
void destroytree(Tree T); 

int main()
{
 biTree T;Tree P;
 createbitree(T);
 desttree(T);
 creatree(P);
 destroytree(P);
 return 0;
}

void createbitree(biTree &T)
{
 char ch;biTree S;
 scanf("%c",&ch);
 if(ch!='#')
 {
  T=(biTree)malloc(sizeof(bitree));
  T->data=ch;
  T->lchild=T->rchild=NULL;
  createbitree(T->lchild);
  createbitree(T->rchild);
 }
}
void desttree(biTree T)
{
 if(T)
 {
  desttree(T->lchild);
  desttree(T->rchild);
  free(T);
 }
}
int initqueue(squeue *S)
{
 S->data=(Tree *)malloc(sizeof(Tree)*100);
 S->first=S->rear=0;
 S->maxsize=100;
 return 1;
}

int enqueue(squeue *S,Tree T)
{
 S->data[S->rear%S->maxsize]=T;
 S->rear=(S->rear+1)%S->maxsize;
 return 1;
}
Tree gettop(squeue S)
{
 Tree e;
 e=S.data[S.first];
 return e;
}
Tree dequeue(squeue *S)
{
 Tree e;
 e=S->data[S->first];
 S->first=(S->first+1)%S->maxsize;
 return e;
}
void creatree(Tree &T)
{
 char fa,ch;T=NULL;
 Tree S,r,Q;squeue s;initqueue(&s);
 scanf("%c%c",&fa,&ch);
 while(ch!='#')
 {
  S=(Tree)malloc(sizeof(tree));
  S->firstchild=S->nextsibling=NULL;
  S->data=ch;
  enqueue(&s,S);
  if(fa=='#')
   T=S;
  else
  {
   Q=gettop(s);
   while(Q->data!=fa)
   {
    Q=dequeue(&s);
    Q=gettop(s);
   }
   if(Q->firstchild==NULL)
   {
    Q->firstchild=S;r=S;
   }
   else
   {
    r->nextsibling=S;r=S;
   }
  }
  scanf("%c%c",&fa,&ch);
 }
}

void disptree(Tree T)
{
 Tree P;
 for(P=T;P;P=P->nextsibling)
 {
  printf("%c",P->data);
  if(P->firstchild)
   disptree(P->firstchild);
 }
}
void destroytree(Tree T)
{
 if(T)
 {
  destroytree(T->firstchild);
  destroytree(T->nextsibling);
  free(T);
 }
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值