A1020
Description:
假设二叉树中的key都是不同的正整数,给出后序和中序遍历序列,求这棵树的层次遍历序列
Input:
- 一个测试一组样例
- 首行正整数N<=30,代表二叉树中所有的数字节点个数
- 第二行给出后序序列,第三行给出中序序列
7 2 3 1 5 7 6 4 1 2 3 4 5 6 7
Output:
对于每个测试样例,输出一行层次遍历序列,数字由空格隔开
4 1 6 3 5 7 2
算法构思:
关键是根据后序序列(左右根)和中序序列(左根右)特性构建二叉树,代码不难:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 35;
struct Node{
int data;
Node* lchild; //左子树
Node* rchild; //右子树
};
Node* CreateNode(int n){
Node* anode = new Node;
anode->data = n;
anode->lchild = nullptr;
anode->rchild = nullptr;
return anode;
}
int n;
int pre[maxn], in[maxn], post[maxn]; //前序, 中序, 后序
map<int, int>postIndex; //返回后序序列中的位置
map<int, int>inIndex; //返回中序序列中的位置
Node* BinaryTree = nullptr;
Node* constructTree(int postL, int postR, int inL, int inR){
if(postL > postR)
return nullptr;
int rootDa = post[postR];
Node* root = CreateNode(rootDa);
int rnum = inR - inIndex[rootDa];
int lnum = inIndex[rootDa] - inL;
root->rchild = constructTree(postR-rnum, postR-1, inIndex[rootDa]+1, inIndex[rootDa]+rnum);
root->lchild = constructTree(postL, postL+lnum-1, inL, inIndex[rootDa]-1);
return root;
}
void BFS(){
queue<Node*>ans;
ans.push(BinaryTree);
printf("%d", ans.front()->data);
while(!ans.empty()){
Node* now = ans.front();
if(now->lchild != nullptr) ans.push(now->lchild);
if(now->rchild != nullptr) ans.push(now->rchild);
if(now != BinaryTree) printf(" %d", now->data);
ans.pop();
}
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", &post[i]);
postIndex.insert(pair<int, int>(post[i], i));
}
for(int i = 0; i < n; i++){
scanf("%d", &in[i]);
inIndex.insert(pair<int, int>(in[i], i));
}
BinaryTree = constructTree(0, n-1, 0, n-1);
BFS();
return 0;
}