参考:http://blog.csdn.net/yong369044325/article/details/7901008
用递归方法,先找出根节点,然后分左右进行递归重建。注意根节点要按引用传递。
广度优先遍历则用队列实现。根节点入队,队不空时,先对队前访问,并弹出,若左不空,则左子树入队,右子树同样。
#include <iostream>
#include <string>
#include <list>
using namespace std;
class Node
{
public:
Node(char a = '0')
{
v = a;
left = nullptr;
right = nullptr;
}
Node *left;
Node *right;
char v;
};
void Rebuilt(string pre, string in, int length, Node** root)
{
if (!pre.length() && !in.length())
{
return;
}
Node* p = new Node(pre[0]);
if (*root == nullptr)
{
*root = p;
}
if (length == 1)
{
return;
}
int pos = in.find(pre[0]);
int leftL = pos;
int rightL = length - pos - 1;
if (leftL > 0)
{
Rebuilt(pre.substr(1), in, leftL, &((*root)->left));
}
if (rightL > 0)
{
Rebuilt(pre.substr(leftL + 1), in.substr(leftL + 1), rightL, &((*root)->right));
}
}
int main()
{
int t;
cin >> t;
while (t--)
{
string a, b;
Node* root = nullptr;
cin >> a >> b;
Rebuilt(a, b, a.length(), &root);
list<Node*> LL;
LL.push_back(root);
while (!LL.empty())
{
Node* p = LL.front();
LL.pop_front();
cout << p->v ;
if (p->left != nullptr)
{
LL.push_back(p->left);
}
if (p->right != nullptr)
{
LL.push_back(p->right);
}
}
cout << endl;
}
}