1、题目描述
给出一个二叉树的 前序 与 中序 遍历结果,求出其后序遍历结果。如
输入:“ABEFCD”
,“EBFADC”
输出:”EFBDCA“
2、解题
2.1 思路
思路之一,即通过前序与中序的遍历结果,先求出原二叉树的排列,然后再对二叉树作后序遍历。
思路之二,直接根据前序与中序结果,求出后序遍历结果。
下面的实现是基于第二个思路!
2.2 代码
#include<iostream>
#include<string>
using namespace std;
int getPos(char c, string inStr)
{
int pos;
for (pos = 0; pos < inStr.size(); pos++)
{
if (inStr[pos] == c)
break;
}
return pos;
}
void func(int prelidx, int preridx, int inlidx, int inridx, string preStr, string inStr, string& ans)
{
int pos = getPos(preStr[prelidx], inStr);//以前序中节点找寻中序中的位置,以此判断当前根节点的左右子树长度
int tmpl = pos - inlidx;//左子树的长度
int tmpr = inridx - pos;//右子树的长度
if (pos > inlidx)
func(prelidx + 1, prelidx + tmpl, inlidx, pos - 1, preStr, inStr, ans);
if (pos < inridx)
func(preridx - tmpr + 1, preridx, pos + 1, inridx, preStr, inStr, ans);
ans.push_back(preStr[prelidx]);
}
string postorderString(string postorderString, string inorderString)
{
int sz = inorderString.size();
string ans;
func(0, sz - 1, 0, sz - 1, postorderString, inorderString, ans);
return ans;
}
int main()
{
string preStr = "ABEFCD";
string inStr = "EBFADC";
string ans = postorderString(preStr, inStr);
cout << "后序遍历结果为:";
cout << ans << endl;
return 0;
}