【PTA 5-10 树的遍历 (25分)】+ 二叉树

来源:互联网 发布:mac os 卸载程序 编辑:程序博客网 时间:2024/04/29 06:02

5-10 树的遍历 (25分)
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:

输入第一行给出一个正整数NN(\le 30≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:

在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:

4 1 6 3 5 7 2

二叉树的遍历有三种方式,如下:

(1)前序遍历(DLR),首先访问根结点,然后遍历左子树,最后遍历右子树。简记根-左-右。

(2)中序遍历(LDR),首先遍历左子树,然后访问根结点,最后遍历右子树。简记左-根-右。

(3)后序遍历(LRD),首先遍历左子树,然后遍历右子树,最后访问根结点。简记左-右-根。

所谓层序遍历 : 往下 一层一层遍历

AC代码:

#include<cstdio>#include<queue>using namespace std;const int K = 35;int h[K],z[K],l[K],r[K];int gz(int l1,int r1,int l2,int r2){    if(l1 > r1) return 0;    int t = h[r2];    int nl = l1;    while(z[nl] != t) nl++;    int nn = nl - l1;    l[t] = gz(l1,nl - 1,l2,l2 + nn - 1);    r[t] = gz(nl + 1,r1,l2 + nn,r2 - 1);    return t;}void sc(int N){    queue <int> q;    int pl = h[N];    printf("%d",pl);    if(l[pl]) q.push(l[pl]);    if(r[pl]) q.push(r[pl]);    while(!q.empty()){        pl = q.front();        q.pop();        printf(" %d",pl);        if(l[pl]) q.push(l[pl]);        if(r[pl]) q.push(r[pl]);    }    return ;}int main(){    int N;    scanf("%d",&N);    for(int i = 1; i <= N; i++)        scanf("%d",&h[i]);    for(int i = 1; i <= N; i++)        scanf("%d",&z[i]);    gz(1,N,1,N);    sc(N);    return 0;}
0 0