!:后序遍历加中序遍历序列构造树,而后对该树进行层序遍历;
#include<iostream>
#include<queue>
#include<stdlib.h>
using namespace std;
struct Node
{
int data;
Node * lchild;
Node * rchild;
}node;
int post[32], in[32];
Node* create(int postL, int postR, int inL, int inR)
{
if(postL > postR) return NULL;
Node * root = new Node;
root->data = post[postR];
int k;
for(k = inL; k <= inR; k++)
{
if(in[k] == post[postR]) break;
} //in序列中查找根节点;
int numleft = k - inL;
root->lchild = create(postL, postL + numleft - 1, inL, k-1);
root->rchild = create(postL + numleft, postR - 1, k + 1, inR);
return root;
}
void LayerOrder(Node * root)
{
queue<Node *> q;
cout << root->data;
if(root->lchild != NULL) q.push(root->lchild);
if(root->rchild != NULL) q.push(root->rchild);
while(!q.empty())
{
Node * now = q.front();
q.pop();
cout << " " << now->data;
if(now->lchild != NULL) q.push(now->lchild);
if(now->rchild != NULL) q.push(now->rchild);
}
cout << endl;
}
int main()
{
int n;
cin >> n;
for(int i = 0; i < n; i++) cin >> post[i];
for(int i = 0; i < n; i++) cin >> in[i];
Node * r = create(0, n-1, 0, n-1);
LayerOrder(r);
system("pause");
return 0;
}