SDUT-1291-数据结构上机测试4.1:二叉树的遍历与应用1
Problem Description
输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。
Input
第一行输入二叉树的先序遍历序列;
第二行输入二叉树的中序遍历序列。
Output
输出该二叉树的后序遍历序列。
Sample Input
ABDCEF
BDAECF
Sample Output
DBEFCA
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//先序遍历的第一个为根节点,就是a[0],再在中序遍历中找到根节点的位置
struct treenode
{
char data;
struct treenode *l;
struct treenode *r;
};
struct treenode *creat(int n, char a[100000], char b[100000])
{
struct treenode *root;
if(n == 0)
return NULL;
else
{
root = (struct treenode *)malloc(sizeof(struct treenode));
root -> data = a[0];
int i;
for(i = 0;i < n;i++)
{
if(b[i] == a[0])
break;//找根节点的位置
}
root -> l = creat(i, a + 1, b);//a+1表示除去第一个数组元素后的新的数组
root -> r = creat(n - i - 1, a + i + 1, b + i + 1);
}
return root;
};
void postorder(struct treenode *root)
{
if(root)
{
postorder(root -> l);
postorder(root -> r);
printf("%c", root -> data);
}
}
int main()
{
char a[100000], b[100000];
struct treenode *root;
gets(a);
gets(b);
int n = strlen(a);
root = creat(n, a, b);
postorder(root);
return 0;
}