A1020 Tree Traversals [中序后序建树]
题目大意:给你中序后序,要求输出层序。
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 50;
struct node
{
int data;
node* left, * right;
};
int pre[maxn], in[maxn], post[maxn];
int n;
node* create(int postl, int postr, int inl, int inr)
{
if (postl > postr)
return NULL;
node* root = new node;
root->data = post[postr];
int i;
for (i = inl; i <= inr; i++)
{
if (in[i] == post[postr])
break;
}
int numLeft = i - inl;
root->left = create(postl, postl + numLeft-1, inl, i - 1);
root->right = create(postl + numLeft, postr - 1, i + 1, inr);
return root;
}
int num = 0;
void bfs(node* root)
{
queue<node*>q;
q.push(root);
while (!q.empty())
{
node* now = q.front();
q.pop();
cout << now->data;
num++;
if (num < n) cout << " ";
if (now->left != NULL) q.push(now->left);
if (now->right != NULL) q.push(now->right);
}
}
int main()
{
node* T;
cin >> n;
for (int i = 0; i < n; i++)
cin >> post[i];
for (int i = 0; i < n; i++)
cin >> in[i];
T = create(0,n-1,0,n-1);
bfs(T);
return 0;
}