注:只知道前序后序不一定能确定唯一的二叉树,因为只能确定父子节点而无法确定左右子树。
前序中序转后序
算法描述
1在前序序列中找到根节点
2在中序序列中查找这个根节点,确定左右子树。
3对左右子树递归进行步骤1,2。
4输出根节点
递归实现
#include<iostream>
#include<string>
using namespace std;
string pre, in;
void creatTree(int s, int e, int rootindex) {//s,e,中序的子树范围,前序中的根节点下标
if (s <=e) {//递归出口s>e
int index = s;
while (in[index] != pre[rootindex]) { index++; }//在中序中查找根节点。
creatTree(s, index - 1, rootindex + 1);//左子树
creatTree(index + 1, e, rootindex + 1 + (index - s));//右子树
cout << in[index];//根节点
}
}
int main() {
cin >> pre >> in;
creatTree(0, in.size() - 1, 0);
return 0;
}
/*数据前序中序
ACDEFHGB
DECAHFBG
结果
EDCHBGFA*/
后序中序转前序
算法描述
1在后序序列中找到根节点
2在中序序列中找到该根节点的位置,确定左右子树范围
3输出根节点
3对左右子树递归重复步骤1,2,3。
递归代码
#include<iostream>
#include<string>
using namespace std;
string post, in;
void creatTree(int s, int e, int rootindex) {//s,e,中序的子树范围,后序中的根节点下标
if (s <=e) {//递归出口s>e
int index = s;
while (in[index] != post[rootindex]) { index++; }//在中序中查找根节点。
cout << in[index];//根节点
creatTree(s, index - 1, rootindex -1-(e-index));//左子树
creatTree(index + 1, e, rootindex -1);//右子树
}
}
int main() {
cin >> in >> post;
creatTree(0, in.size() - 1, post.size() - 1);
return 0;
}
/*数据中序后序
ADEFGHMZ
AEFDHZMG
输出
GDAFEMHZ
*/