标签:二叉树
题目链接:点击打开链接
解题思路:
很不错的一道题。用递归的方法求解。每次对两个序列进行递归,求得左子树的先序/中序,右子树的先序/中序。把树建好后调用递归输出后序即可
完整代码:
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
string fir , mid;
typedef struct Node
{
char ch;
struct Node *l;
struct Node *r;
Node()
{
l = NULL;
r = NULL;
};
}node;
void print(node *tree)
{
if(tree == NULL) return;
print(tree->l);
print(tree->r);
cout << tree->ch;
}
void creat(node *&tree , string fir , string mid)
{
if(fir.length() == 0) return ;
node *temp = new node();
temp->ch = fir[0];
tree = temp;
int len = mid.find(fir[0]);
string Lmid(mid , 0 , len);
string Rmid(mid , len + 1 , mid.length() - len - 1);
string Lfir(fir , 1 , len);
string Rfir(fir , len + 1 , fir.length() - len - 1);
creat(tree->l , Lfir , Lmid);
creat(tree->r , Rfir , Rmid);
}
int main()
{
#ifdef DoubleQ
freopen("in.txt" , "r" , stdin);
#endif // DoubleQ
while(cin >> fir >> mid)
{
node *tree = NULL;
creat(tree , fir , mid);
print(tree);
cout << endl;
}
}
标签:二叉树
原文地址:http://blog.csdn.net/u013447865/article/details/45440385