- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- char a[100000],b[100000];
- struct node
- {
- char data;
- struct node *l,*r;
- };
- struct node *creat(char *a,char *b,int n)//重建树
- {
- if(n<=0)
- return NULL;
- struct node *root;
- root=(struct node *)malloc(sizeof(struct node));
- root->data=*a;
- int i;
- for(i=0; i<n; i++)
- {
- if(b[i]==*a)
- break;
- }
- root->l=creat(a+1,b,i);//左右分开建树
- root->r=creat(a+i+1,b+i+1,n-i-1);
- return root;
- }
- void last(struct node *root)//后序遍历
- {
- if(root!=NULL)
- {
- last(root->l);
- last(root->r);
- printf("%c",root->data);
- }
- }
- void ceng(struct node *root)//层次遍历
- {
- struct node *z[100000],*p;//用栈进行左右层次遍历
- int jin,chu;
- jin=chu=0;
- z[jin++]=root;
- while(chu<jin)
- {
- p=z[chu++];
- printf("%c",p->data);
- if(p->l!=NULL)
- z[jin++]=p->l;
- if(p->r!=NULL)
- z[jin++]=p->r;
- }
- }
- int main()
- {
- int t,len;
- scanf("%d",&t);
- struct node *root;
- while(t--)
- {
- scanf("%s",a);
- scanf("%s",b);
- len=strlen(a);
- root=creat(a,b,len);
- last(root);
- printf("\n");
- ceng(root);
- printf("\n");
- }
- return 0;
- }
知道先序和中序,求后序以及层次遍历
最新推荐文章于 2022-06-09 23:09:51 发布