求二叉树的先序遍历
Problem Description
已知一棵二叉树的中序遍历和后序遍历,求二叉树的先序遍历
Input
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的中序遍历序列,第二个字符串表示二叉树的后序遍历序列。
Output
输出二叉树的先序遍历序列
Sample Input
2
dbgeafc
dgebfca
lnixu
linux
Sample Output
abdegcf
xnliu
类似的问题:前序遍历,中序遍历,后续遍历,任意给出两个就能求出另一个吗?
答案是不能,给出的两个中,必须包含中序遍历。
分析:
- 根据后序遍历序列最后一个结点确定根结点;
- 根据根结点在中序遍历序列中分割出左右两个子序列;
- 对左子树和右子树分别递归使用相同的方法继续分解。
给出代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
char date;
struct node *l, *r;
} tree;
tree* treenew(); // 创建新结点
tree* creat( int len, char last[], char mid[] ); //根据后序和中序构造二叉树
void show_pre( tree* root ); // 前序遍历二叉树
int main()
{
int pp,list;
char mid[101] = "";
char last[101] = "";
scanf("%d",&list);
for ( pp=0; pp<list; pp++ ) {
scanf("%s %s",mid,last);
tree *root;
root = treenew();
int len = strlen(mid);
root = creat( len, last, mid );
show_pre(root);
printf("\n");
}
return 0;
}
tree* treenew()
{
tree *p;
p = (tree *)malloc(sizeof(tree));
p->l = p->r = NULL;
return p;
}
tree* creat( int len, char last[], char mid[] )
{
if ( len<=0 ) {
return NULL;
}
tree *root = treenew();
root -> date = last[len-1];
int i;
for ( i=0; i<len; i++ ) {
if ( last[len-1] == mid[i] ) {
break;
}
}
root -> l = creat(i,last,mid);
root -> r = creat(len-i-1,last+i,mid+i+1);
return root;
}
void show_pre( tree* root )
{
if ( root ) {
printf("%c",root->date);
show_pre(root->l);
show_pre(root->r);
}
}
/***************************************************
User name: rj180323石旭
Result: Accepted
Take time: 0ms
Take Memory: 144KB
Submit time: 2019-01-21 19:59:47
****************************************************/