树的遍历 (25分)
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数NN(\le 30≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
观察树的中序和后序序列,可以发现后序序列的最后一项为整棵树的根,在中序序列中,这个点把树分为左右两部分,然后又是前面的步骤,观察清楚后我们就可以用递归把树构建出来,最后bfs层次遍历就行了。
代码如下:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
using namespace std;
typedef long long LL;
#define CLR(a,b) memset(a,b,sizeof(a))
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
vector<int> last;
vector<int> mid;
int n;
struct node
{
int num;
node *LC,*RC;
};
int findPos(int x)
{
for (int i = 0 ; i < n ; i++)
if (mid[i] == x)
return i;
}
node* findChild(int l,int r)
{
if (r < l)
return NULL;
node *p;
p = new node;
int num;
int pos = -1;
for (int i = l ; i <= r ; i++)
{
for (int j = 0 ; j < n ; j++)
{
if (last[j] == mid[i])
{
if (j > pos)
{
pos = j;
num = last[j];
break;
}
}
}
}
for (int i = l ; i <= r ; i++)
{
if (mid[i] == last[pos])
{
pos = i;
break;
}
}
p->num = num;
p->LC = findChild(l,pos-1);
p->RC = findChild(pos+1,r);
return p;
}
void bfs(node *root)
{
queue<node*> q;
cout << root->num;
if (root->LC != NULL)
q.push(root->LC);
if (root->RC != NULL)
q.push(root->RC);
node *pr;
while (!q.empty())
{
pr = q.front();
q.pop();
cout << ' ' << pr->num;
if (pr->LC != NULL)
q.push(pr->LC);
if (pr->RC != NULL)
q.push(pr->RC);
}
cout << endl;
}
int main()
{
int t;
cin >> n;
int l = 0;
int r = n-1;
for (int i = 1 ; i <= n ; i++)
{
cin >> t;
last.push_back(t);
}
for (int i = 1 ; i <= n ; i++)
{
cin >> t;
mid.push_back(t);
}
node *p;
p = new node;
p->num = last[n-1];
int pos = findPos(last[n-1]);
p->LC = findChild(l,pos-1);
p->RC = findChild(pos+1,r);
bfs(p);
return 0;
}