A1020 Tree Traversals (25 分)

时间:2021-11-03 00:49:12

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 (≤), 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<cstdio>
#include<queue>
using namespace std;
int post[],in[];
struct node{
int data;
node *lchild;
node *rchild;
};
node *create(int postL,int postR,int inL,int inR){
if(postL>postR){
return NULL;
}
node *root=new node;
root->data=post[postR];
int k;
for(k=inL;k<=inR;k++){
if(post[postR]==in[k]){
break;
}
}
int numleft=k-inL;
root->lchild=create(postL,postL+numleft-,inL,k-);//这里经常出错
root->rchild=create(postL+numleft,postR-,k+,inR);
return root;
}
void LayerOrder(node*root,int k){
if(root==NULL){
return;
}
queue<node*> q;
q.push(root);
while(!q.empty()){
node *now=q.front();
q.pop();
if(k!=){
printf("%d ",now->data);
k--;
}else{
printf("%d",now->data);
}
if(now->lchild!=NULL){
q.push(now->lchild);
}
if(now->rchild!=NULL){
q.push(now->rchild);
}
}
}
int main(){
int n;
scanf("%d",&n);
for(int i=;i<n;i++){
scanf("%d",&post[i]);
}
for(int i=;i<n;i++){
scanf("%d",&in[i]);
}
node *p=create(,n-,,n-);
LayerOrder(p,n);
return ;
}

Mist Note: 解决本题,本小编的思路是,先利用中序和后序序列重建二叉树,然后再层序遍历这棵树。

很多算法还是基础的,主要是在递归重建那里经常出问题。左子树和右子树的递归。

root->lchild=create(postL,postL+numleft-1,inL,k-);

root->rchild=create(postL+numleft,postR-,k+,inR);

红色部分经常出错,切记,我们在写代码的时候,经常是利用数组,而数组是以0开始的,而numleft是个数,你加之后,肯定需要-1,才符合定义,不要混淆。

本题还需要注意输出格式,最后层序遍历的最后一个节点,是不需要空格的。