问题描述:输入树的中序和后序排列,输出树的层次遍历
输入:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
#include<iostream>
#include<queue>
using namespace std;
const int maxn = 10010;
int in[maxn];
int post[maxn];
struct node
{
int val;
node* left;
node* right;
node(int val1) {
val = val1;
}
};
queue<node*> treeq;
node* create(int ina, int inb, int posta, int postb)
{
if (posta > postb)
return NULL;
node* temp = new node(post[postb]);
int a = 0;
for (int i = ina;i <= inb;i++)
{
if (in[i] == post[postb])
{
a = i;
break;
}
}
int numl = a - ina;
temp->left = create(ina,a-1, posta, posta + numl - 1);
temp->right = create(a + 1, inb, posta + numl, postb-1);
return temp;
}
void layerorder(node* root)
{
treeq.push(root);
while (!treeq.empty())
{
node* temp;
temp = treeq.front();
cout << temp->val << " ";
treeq.pop();
if(temp->left!=NULL)
treeq.push(temp->left);
if (temp->right != NULL)
treeq.push(temp->right);
}
}
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* root=create(0, n - 1, 0, n - 1);
layerorder(root);
}