已知一棵二叉树的中序遍历和后序遍历,求二叉树的先序遍历
输入
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的中序遍历序列,第二个字符串表示二叉树的后序遍历序列。
输出
输出二叉树的先序遍历序列
示例输入
2 dbgeafc dgebfca lnixu linux
示例输出
abdegcf xnliu
#include <stdio.h> #include <stdlib.h> #include <string.h> struct node { struct node *left; struct node *right; char data; }; struct node *make(char* a, char* b, int n) { struct node * now; if(n == 0) { return NULL; } now = (struct node *)malloc(sizeof(struct node)); now->data = *(b+n-1);//后序排序最后一个字符 肯定是root 即第一个结点 printf("%c",now->data); //先序排序的遍历方式 int k; for(k = 0;k < n; k++) //在 中序排序中找到 root 结点 { if(a[k] == *(b+n-1)) break; } now->left = make(a, b , k); //构建左分支 now->right = make(a + k + 1, b + k , n - k - 1); //构建右分支 return now; } int main() { char b[1000];//中 char a[1000];//后 int T; while(~scanf("%d",&T)) { while(T--) { memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); scanf("%s",a); scanf("%s",b); int n = strlen(b); make(a, b, n); printf("\n"); } } return 0; }