1020. Tree Traversals (25)
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
第一种方法(中规中矩)
将后序遍历和中序遍历处理成二叉树
在进行层次遍历
#include <iostream>
#include <queue>
#include <cstdio>
#include <cstdlib>
using namespace std;
const int MAX = 32;
int n;
struct Tree{
Tree *le;
Tree *ri;
int data;
};
Tree *root;
int pos[MAX];
int in[MAX];
Tree *buildTree(int pl,int pr,int il,int ir){
if(pl>pr)return NULL;
int p = il;
while (in[p] != pos[pr])++p;
Tree *tree = (Tree *)malloc(sizeof(Tree));
tree->data = pos[pr];
tree->le = buildTree(pl,pr-ir+p-1,il,p-1);
tree->ri = buildTree(pr-ir+p,pr-1,p+1,ir);
return tree;
}
void printLevelTree(Tree *root){
queue<Tree *> que;
Tree *Tr = NULL;
que.push(root);
int num = 0;
while(!que.empty()){
Tree *Tr = que.front();
que.pop();
if(Tr==NULL)continue;
printf("%d",Tr->data);
num++;
if(num<n)printf(" ");
que.push(Tr->le);
que.push(Tr->ri);
}
}
int main(){
int i;
Tree *root;
scanf("%d",&n);
for(i=0;i<n;++i){
scanf("%d",&pos[i]);
}
for(i=0;i<n;++i){
scanf("%d",&in[i]);
}
root=buildTree(0,n-1,0,n-1);
printLevelTree(root);
return 0;
}
方法二(简便算法)
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
const int MAX = 32;
int pos[MAX],in[MAX];
int n;
struct T{
int Tpl,Tpr,Til,Tir;
};
queue<T> q;
void printLevel(int pl,int pr,int il,int ir){
T t;
t.Tpl = pl,t.Tpr = pr,t.Til = il,t.Tir = ir;
q.push(t);
bool temp = false;
while(!q.empty()){
t = q.front();
q.pop();
int p = t.Til;
while(in[p] != pos[t.Tpr])p++;
if(temp == true){
printf(" %d",in[p]);
}else{
printf("%d",in[p]);
}
temp = true;
T temp;
temp.Tpl = t.Tpl,temp.Tpr = t.Tpr-t.Tir+p-1,temp.Til = t.Til,temp.Tir = p-1;
if(temp.Tpl<=temp.Tpr)q.push(temp);
temp.Tpl = t.Tpr-t.Tir+p,temp.Tpr = t.Tpr-1,temp.Til = p+1,temp.Tir = t.Tir;
if(temp.Tpl<=temp.Tpr)q.push(temp);
}
}
int main(){
int i;
scanf("%d",&n);
for(i = 0 ; i < n ; i++)scanf("%d",&pos[i]);
for(i = 0 ; i < n ; i++)scanf("%d",&in[i]);
printLevel(0,n-1,0,n-1);
}