这里参考了一位大神的代码,写法很简洁,思路其实就是这样,学过先中后序遍历的人,基本上都能看懂。
每次进入递归程序之后,就找到根节点,然后把左子树传给递归程序,然后把右子树传给子递归程序,然后输出这个根节点。
#include <iostream>
#include <string>
using namespace std;
void post_order(const char *pre,const char *in,int len)
{
if (len<1)
return ;
int i = 0;
while (in[i]!=pre[0])
i++;
post_order(pre + 1, in, i);
post_order(pre + i + 1, in + i + 1, len - i - 1);
cout << pre[0];
}
int main()
{
string pre, in;
cin >> pre >> in;
post_order(pre.c_str(), in.c_str(), in.size());
return 0;
} // c_str()返回的是 const char * 不能直接赋值给 char*