A1020 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 (≤), 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

 1 #include<cstdio>
 2 #include<queue>
 3 using namespace std;
 4 int post[32],in[32];
 5 struct node{
 6     int data;
 7     node *lchild;
 8     node *rchild;
 9 };
10 node *create(int postL,int postR,int inL,int inR){
11     if(postL>postR){
12         return NULL;
13     }
14     node *root=new node;
15     root->data=post[postR];
16     int k;
17     for(k=inL;k<=inR;k++){
18         if(post[postR]==in[k]){
19             break;
20         }
21     }
22     int numleft=k-inL;
23     root->lchild=create(postL,postL+numleft-1,inL,k-1);//这里经常出错
24     root->rchild=create(postL+numleft,postR-1,k+1,inR);
25     return root;
26 }
27 void LayerOrder(node*root,int k){
28     if(root==NULL){
29         return;
30     }
31     queue<node*> q;
32     q.push(root);
33     while(!q.empty()){
34         node *now=q.front();
35         q.pop();
36         if(k!=1){
37             printf("%d ",now->data);
38             k--;
39         }else{
40             printf("%d",now->data);
41         }
42         if(now->lchild!=NULL){
43             q.push(now->lchild);
44         }
45         if(now->rchild!=NULL){
46             q.push(now->rchild);
47         }
48     }
49 }
50 int main(){
51     int n;
52     scanf("%d",&n);
53     for(int i=0;i<n;i++){
54         scanf("%d",&post[i]);
55     }
56     for(int i=0;i<n;i++){
57         scanf("%d",&in[i]);
58     }
59     node *p=create(0,n-1,0,n-1);
60     LayerOrder(p,n);
61     return 0;
62 } 

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

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

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

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

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

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

 

猜你喜欢

转载自www.cnblogs.com/mist2019/p/10364397.html