Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
题意:给定长为n的后序序列和中序序列,输出层序序列。
思路:建树,再用bfs。 或者直接在建树时用二维vector存储。
代码【vector存储】:
#include <iostream>
#include <sstream>
#include <string>
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 30+5;
const ll INF = 0x3f3f3f3f;
const double eps=1e-4;
const int T=3;
struct Node {
int data;
Node *lchild,*rchild;
};
int post[N],in[N],n;
queue<Node*>que;
Node* root;
vector<vector<int> >bt(N);
///array1[]为中序序列,array2[]为后序序列
void build(int n,int array1[],int array2[],const int depth) {
if(n<=0)
return ;
int i=0;
while(array1[i]!=array2[n-1]) {
i++;///找根
}
bt[depth].push_back(array1[i]);
build(i,array1,array2,depth+1);
build(n-i-1,array1+i+1,array2+i,depth+1);
}
void bfs() {
cout<<bt[0][0];
for(int i=1; i<bt.size(); i++) {
for(int j=0; j<bt[i].size(); j++) {
cout<<" "<<bt[i][j];
}
}
}
int main() {
cin>>n;
for(int i=0; i<n; i++)
cin>>post[i];
for(int i=0; i<n; i++)
cin>>in[i];
build(n,in,post,0);
bfs();
return 0;
}
代码【bfs】:
#include <iostream>
#include <sstream>
#include <string>
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 30+5;
const ll INF = 0x3f3f3f3f;
const double eps=1e-4;
const int T=3;
struct Node {
int data;
Node *lchild,*rchild;
};
///array1[]为中序序列,array2[]为后序序列
Node* build(int n,int array1[],int array2[]) {
if(n<=0)
return NULL;
int i=0;
while(array1[i]!=array2[n-1]) {
i++;///找根
}
Node *root=new Node;
root->data=array1[i];
root->lchild=build(i,array1,array2);
root->rchild=build(n-i-1,array1+i+1,array2+i);
return root;
}
queue<Node*>que;
Node* root;
void bfs() {
bool flag=0;
while(!que.empty()) {
root=que.front();
que.pop();
if(root->lchild!=NULL) {
que.push(root->lchild);
}
if(root->rchild!=NULL) {
que.push(root->rchild);
}
if(flag) {
cout<<" ";
}
cout<<root->data;
flag=1;
}
}
int post[N],in[N];
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];
root=new Node;
root->lchild=root->rchild=NULL;
root=build(n,in,post);
que.push(root);
bfs();
return 0;
}