PAT【L2-006 树的遍历】
L2-006 树的遍历(25 分)
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2题解:先根据二叉树的后序和中序遍历建立二叉树,然后再层序输出即可。建立二叉树的过程就是一个递归过程。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
using namespace std;
int cnt=0;
int pre[33];
typedef struct node{
int data;
node *lchild,*rchild;
}BiTNode,*BiTree;
node* toPre(int post[],int in[],int n){
if(n<=0) return NULL;
int t,root=post[n-1];
BiTree T;
T = new BiTNode;
T->lchild=NULL;
T->rchild=NULL;
for(int i=0;i<n;i++){
if(in[i]==root){
t=i;
break;
}
}
T->data=root;
T->lchild=toPre(post,in,t);
T->rchild=toPre(post+t,in+t+1,n-t-1);
return T;
}
void levelOrder(BiTree T){
queue<BiTree> q;
q.push(T);
int i=0;
while(!q.empty()){
BiTree t;
t=q.front();
q.pop();
pre[i++]=t->data;
if(t->lchild) q.push(t->lchild);
if(t->rchild) q.push(t->rchild);
}
}
int main()
{
int post[33],in[33];
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>post[i];
}
for(int i=0;i<n;i++){
cin>>in[i];
}
BiTree T;
T=new BiTNode;
T->lchild=NULL;
T->rchild=NULL;
T=toPre(post,in,n);
levelOrder(T);
for(int i=0;i<n-1;i++){
printf("%d ",pre[i]);
}
printf("%d\n",pre[n-1]);
return 0;
}
浙公网安备 33010602011771号