输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。
输入
第一行输入二叉树的先序遍历序列;
第二行输入二叉树的中序遍历序列。
输出
输出该二叉树的后序遍历序列。
示例输入
ABDCEF
BDAECF示例输出
DBEFCA
#include<stdio.h> #include<stdlib.h> #include<string.h> struct node { char data; struct node *left; struct node *right; }N; struct node *make(char *a,char *b,int n) //由先序遍历序列和中序遍历序列生成二叉树 { struct node *now;//开辟临时结点 char *p;//建立游动指针 int k = 0; if(n<=0) { return NULL; } now=(struct node*)malloc(sizeof(struct node)); (*now).data=*a;//在先序遍历中取得根结点(即第一个字符肯定是二叉树的root) for(p=b;p<b+n;p++)//在中序遍历进行查找,找到则结束循环(必然可以找到) {//p=b <=> p=&b[0];p<n+b =>指向最后一个元素结束 if(*p==*a) break;//在中序遍历中找根结点 root } k = p - b;//左子树的结点数 b <=> &b[0] , p储存 root的地址 (*now).left=make(a+1,b,k); //建立 root 的左分支,回溯 (*now).right=make(a+1+k,p+1,n-k-1);//建立 右分支,回溯 return now; } void lastord(struct node *t) //后序遍历二叉树的函数 { if(t==NULL) return ; lastord(t->left);//先左 遍历 lastord(t->right);//再右 遍历 printf("%c",t->data); } int main() { struct node *tree; char a[100],b[100]; scanf("%s",a); scanf("%s",b); int n=strlen(a); tree=make(a,b,n); lastord(tree); printf("\n"); return 0; }