编写一个程序,输入一颗二叉树的先序遍历和中序遍历,输出其后序遍历
#include<iostream>
#include<string>
using namespace std;
void outPostOrder(string pre, string mid)
{
int len = pre.length();
if (len == 1)
{
cout << pre[0];
return;
}
int index = mid.find(pre[0]);
string leftPre(pre, 1, index);
string leftMid(mid, 0, index);
string rightPre(pre, index + 1, len - index - 1);
string rightMid(mid, index + 1, len - index - 1);
if (leftPre.length() > 0)
outPostOrder(leftPre, leftMid);
if (rightPre.length() > 0)
outPostOrder(rightPre, rightMid);
cout << endl;
}
int main()
{
string pre, mid;
cout << "请输入先序遍历序列: ";
cin >>pre;
cout << "请输入中序遍历序列: ";
cin >> mid;
cout << "后序遍历序列为: ";
outPostOrder(pre, mid);
cout << endl;
return 0;
}