对于二叉数T,可以递归定义它的先序遍历,中序遍历和后序遍历如下:
先序:根左右
中序:左根右
后序:左右根
输入一棵二叉树的先序遍历和中序遍历序列,输出它的后序遍历序列。
样例输入:
DBACEGF ABCDEFG
BCAD CAD
样例输出:
ACBFGED
CDAB
分析:先序遍历的第一个字符就是根,因此只需在中序遍历中找到它,就知道左右子树的先序和后序遍历。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N=256;
char s1[N],s2[N];
void build(int n,char* s1,char* s2)
{
if(n<=0) return ;
int p=strchr(s2,s1[0])-s2; //找到根结点在中序遍历的中的位置
build(p,s1+1,s2); // 递归构造左子树的后序遍历
build(n-p-1,s1+p+1,s2+p+1);// 递归构造右子树的后序遍历
cout<<s1[0]; // 把根结点添加到最后
}
int main()
{
int n;
while(cin>>s1>>s2)
{
n=strlen(s1);
build(n,s1,s2);
}
return 0;
}
给出一棵二叉树的中序与后序排列。求出它的先序排列。
样例输入:
BADC BDCA
样例输出:
ABCD
链接网址:http://tyvj.cn/Problem_Show.asp?id=1441
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=256;
char s1[N],s2[N];
void build(int n,char* s1,char* s2)
{
if(n<=0) return ;
int p=strchr(s2,s1[n-1])-s2;//找到根结点在中序遍历的中的位置
cout<<s1[n-1]; // 把根结点添加到最前
build(p,s1,s2); // 递归构造左子树的后序遍历
build(n-1-p,s1+p,s2+p+1); // 递归构造右子树的后序遍历
}
int main()
{
int n;
char ans[N];
cin>>s2>>s1;{
n=strlen(s2);
build(n,s1,s2);
cout<<endl;
}
return 0;
}