求二叉树的先序遍历 SDUT

78 阅读1分钟

求二叉树的先序遍历

Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^

题目描述

 已知一棵二叉树的中序遍历和后序遍历,求二叉树的先序遍历

输入

 输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的中序遍历序列,第二个字符串表示二叉树的后序遍历序列。 

输出

 输出二叉树的先序遍历序列

示例输入

2
dbgeafc
dgebfca
lnixu
linux

示例输出

abdegcf
xnliu
 
因为头文件写错就是编译不过<string>。。。。
 
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
char pre[100],mid[100],post[100];
int s;
int solo(int k,char *mid,char *post)
{
	if(k<=0)//返回控制条件
	{
		return 0;
	}
	pre[s++]=post[k-1];//将节点进站
	char *p=strchr(mid,post[k-1]);//找到post[]的节点在mid[]中的位置
	int l=p-mid;
	solo(l,mid,post);//分别递归左右子树
	solo(k-l-1,p+1,post+l);
}
int main()
{
	int n,k;
	scanf("%d",&n);
	while(n--)
	{
		s=0;
		scanf("%s%s",mid,post);
		k=strlen(post);
		solo(k,mid,post);//进行调用并没有把树建初来
		pre[s]='\0';
		puts(pre);
	}
	return 0;
}