求二叉樹的先序遍歷
題目描述
已知一棵二叉樹的中序遍歷和後序遍歷,求二叉樹的先序遍歷
輸入
輸入數據有多組,第一行是一個整數t (t<1000),代表有t組測試數據。每組包括兩個長度小於50 的字符串,第一個字符串表示二叉樹的中序遍歷序列,第二個字符串表示二叉樹的後序遍歷序列。
輸出
輸出二叉樹的先序遍歷序列
示例輸入
2 dbgeafc dgebfca lnixu linux
示例輸出
abdegcf xnliu
#include <bits/stdc++.h>
using namespace std;
typedef struct node
{
char data;
struct node *l,*r;
} tree;
tree *creat(int len,char *in,char *last)
/*中序遍歷中根節點的左邊全都是左子樹的中序,
右邊全是右子樹中序。然而每個子樹的先序序列的第一個節點是
子樹的根,而且向後移動中序查找得到的左子樹節點數便可分開
得到左右子樹。因此可以用遞歸分而治之*/
{
tree *head; //創立根節點
if(len==0)
{
return NULL; //節點爲零時,表示數據完全進入樹中
}
head=new node;
char *p;
head->data=last[len-1]; //先序的第一個節點指定是當前子樹的根
for(p=in; p!=NULL; p++)
if(*p==last[len-1]) break;
int lon=p-in; //左子樹節點的個數
head->l=creat(lon,in,last); //分而治之創建左子樹
head->r=creat(len-lon-1,p+1,last+lon); //分而治之創建右子樹
return head;
}
void pre(tree * root)
{
if(root)
{
printf("%c",root->data);
pre(root->l);
pre(root->r);
}
}
int main()
{
int n;
char s0[1000],s1[1000];
scanf("%d",&n);
getchar();
while(n--)
{
scanf("%s",s0);
scanf("%s",s1);
char *in,*last;
in=s0;
last=s1;
int len=strlen(s1); //節點數
tree *root=creat(len,in,last); //從兩個字符串中找到樹
pre (root); //後序遍歷
puts("");
}
return 0;
}