您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之求二叉树后序遍历和层次遍历

2016-08-09 11:10 369 查看
#include<stdio.h>
#include<string.h>
#include<string.h>
#include<queue>
using namespace std;
typedef struct no
{
char data;
struct no *lc,*rc;
} node;
int i=0;
char a[500],b[500];
node *creat(char *a,char *b,int k)
{

int m;
node *p;
char *c;
if(k<=0)
{
return NULL;
}
else
{p=new node;
p->data=*a;
for(c=b;;c++)
{
if(*c==*a)
break;
}
m=c-b;
p->lc=creat(a+1,b,m);
p->rc=creat(a+m+1,c+1,k-m-1);

}
return p;
}
void ceng(node *p)
{
queue<node*> q;
node *t;
if(p)
{
q.push(p);
printf("%c",p->data);
while(!q.empty())
{
t=q.front();
q.pop();
if(t->lc)
{
printf("%c",t->lc->data);
q.push(t->lc);
}
if(t->rc)
{
printf("%c",t->rc->data);
q.push(t->rc);
}
}
}
}
void last(node *p)
{
if(p)
{
last(p->lc);
last(p->rc);
printf("%c",p->data);
}
}
int main()
{
node *q;
int t;

scanf("%d",&t);
while(t--)
{
memset(a,'\0',sizeof(a));
memset(b,'\0',sizeof(b));
scanf("%s",a);
scanf("%s",b);
int l=strlen(a);
i=0;
q=new node;
q=creat(a,b,l);
last(q);
printf("\n");
ceng(q);
printf("\n");

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: