二叉树由后序(LRD)和中序(LDR)得到前序(DLR)
具体代码
#include<iostream>
#include<string>
using namespace std;
void MidSplitToTwoArray(const int mid, const string zhongxv, string &midleft, string &midright)
{
for (int i = 0; i < zhongxv.size(); i++)
{
if (i < mid)
midleft = midleft + zhongxv[i];
if (i > mid)
midright = midright + zhongxv[i];
}
}
void HouSplitToTwoArray(const int houxvleftsize, const string houxv, string &houleft, string &houright)
{
for (int i = 0; i <= houxv.size() - 2; i++)
{
if (i < houxvleftsize)
houleft = houleft + houxv[i];
if (i >= houxvleftsize)
houright = houright + houxv[i];
}
}
void findRoot(string houxv,string zhongxv)
{
int num = houxv.size();
cout<< houxv[num - 1];
if (num>1)
{
int mid=-1;
for (int i = 0; i < num; i++)
{
if (zhongxv[i] == houxv[num - 1])
{
mid = i;
break;
}
}
string midleft="";
string midright="";
string houleft="";
string houright="";
MidSplitToTwoArray(mid,zhongxv,midleft,midright);
int houxvleftsize = midleft.size();
HouSplitToTwoArray(houxvleftsize,houxv,houleft,houright);
if(midleft.size()!=0 && houleft.size()!=0)
findRoot(houleft, midleft);
if (midright.size() != 0 && houright.size() != 0)
findRoot(houright, midright);
}
}
int main()
{
string houxv;
string zhongxv;
cout << "请输入二叉树的后序遍历:";
getline(cin, houxv);
cout << "请输入二叉树的中序遍历:";
getline(cin, zhongxv);
cout << "得到的先序遍历:";
findRoot(houxv,zhongxv);
return 0;
}
程序运行