Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历。
输入
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。
输出
每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列
示例输入
2 abdegcf dbgeafc xnliu lnixu
示例输出
dgebfca abcdefg linux xnuli
#include<bits/stdc++.h> using namespace std; struct Tree { Tree *left; Tree *right; char data; }; char a[1000]; char b[1000]; Tree *creat(char *p,char *q,int len) { if(len<0) return NULL; Tree *root=new Tree(); root->data=*p; int i; for(i=0;i<=len;i++) { if(*(q+i)==*p)break; } root->left=creat(p+1,q,i-1); root->right=creat(p+i+1,q+i+1,len-i-1); return root; } void houxu(Tree *root) { if(root) { houxu(root->left); houxu(root->right); printf("%c",root->data); } } void cengci(Tree *root) { queue<Tree*>q; Tree * p; q.push(root); while(!q.empty()) { p=q.front(); if(p->left)q.push(p->left); if(p->right)q.push(p->right); printf("%c",p->data); q.pop(); } } int main() { int number; Tree *root; scanf("%d",&number); while(number--) { scanf("%s%s",a,b); root=new Tree(); root=creat(a,b,strlen(a)-1); houxu(root); printf("\n"); cengci(root); printf("\n"); } }