其他分享
首页 > 其他分享> > 数据结构作业之输出树的每一条从根节点到叶节点的路径

数据结构作业之输出树的每一条从根节点到叶节点的路径

作者:互联网

数据结构作业,输出树的每一条从根节点到叶节点的路径


#include <stdio.h>
#include <stdlib.h>
typedef struct tree
{
 char data;
 struct tree *firstchild,*nextsibling;
}tree,*Tree;
typedef struct squeue
{
 Tree *data;
 int first,rear;
 int maxsize;
}Squeue;
int initsqueue(Squeue *S)
{
 S->data=(Tree *)malloc(sizeof(Tree)*100);
 S->first=S->rear=0;
 S->maxsize=100;
 return 1;
}
int enqueue(Squeue *S,Tree e)
{
 S->data[S->rear%S->maxsize]=e;
 S->rear=(S->rear+1)%S->maxsize;
 return 1;
}
Tree dequeue(Squeue *S)
{
 Tree e;
 e=S->data[S->first];
 S->first=(S->first+1)%S->maxsize;
 return e;
}
/*孩子兄弟链表创建树*/ 
void createtree(Tree &T)
{
 Squeue S;
 initsqueue(&S);
 char fa,ch;
 scanf("%c%c",&fa,&ch);
 while(ch!='#')
 {
  Tree P;
  P=(Tree)malloc(sizeof(tree));
  P->data=ch;
  P->firstchild=P->nextsibling=NULL;enqueue(&S,P);
  if(fa=='#')
   T=P;
  else
  {
   Tree e=S.data[S.first];Tree r;
   while(e->data!=fa)
   {
    dequeue(&S);
    e=S.data[S.first];
   }
   if(e->firstchild==NULL)
   {
    e->firstchild=P;r=P;
   }
   else
   {
    r->nextsibling=P;r=P;
   }
  }
  scanf("%c%c",&fa,&ch);
 }
}

typedef struct snode
{
 char *data;
 int top;
}Snode;
int initstack(Snode *S)
{
 S->data=(char *)malloc(sizeof(char)*100);
 S->top=0;
 return 1;
}
int enstack(Snode *S,char e)
{
 S->data[S->top]=e;
 S->top++;
 return 1;
}
char destack(Snode *S)
{
 char e;
 e=S->data[S->top-1];
 S->top--;
 return e;
}
/*输出栈内元素*/ 
void print(Snode S)
{
 int i=0;
 while(i<S.top)
 {
  printf("%c ",S.data[i]);
  i++;
 }
}
/*输出树中每一条从根结点到叶子节点的路径*/ 
void disptree(Tree T,Snode *S)
{
 while(T)
 {
  enstack(S,T->data);
  if(T->firstchild)
   disptree(T->firstchild,S);
  else
  {
   print(*S);printf("\n");
  }
  destack(S);
  T=T->nextsibling;
 }
}
int main()
{
 Tree T;Snode S;initstack(&S);
 createtree(T);
 disptree(T,&S);
}

标签:int,Tree,Snode,char,从根,数据结构,data,节点,first
来源: https://blog.csdn.net/qq_44076232/article/details/95490767