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<bits/stdc++.h>

using namespace std;
const int N=35;
int in[N],post[N];
typedef struct node;
typedef node *tree;
struct node
{
    int data;
    tree L,R;
};
void solve(tree &bt,int l1,int r1,int l2,int r2)
{
    if(l1>r1||l2>r2) return;
    int mid=l2;
    while(in[mid]!=post[r1]) mid++;
    bt=new node;
    bt->data=in[mid];
    bt->L=bt->R=NULL;
    solve(bt->L,l1,l1+mid-l2-1,l2,mid-1);
    solve(bt->R,l1+mid-l2,r1-1,mid+1,r2);

}
vector<int>p;
void leve(tree bt)
{
    queue<tree>Q;
    Q.push(bt);
    while(!Q.empty()){
        tree t=Q.front();
        Q.pop();
        p.push_back(t->data);
        if(t->L){
            Q.push(t->L);
        }
        if(t->R){
            Q.push(t->R);
        }
    }
}
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",&post[i]);
    }
    for(int i=0;i<n;i++){
        scanf("%d",&in[i]);
    }
    tree bt;
    bt=NULL;
    solve(bt,0,n-1,0,n-1);
    leve(bt);
    for(int i=0;i<p.size();i++){
        if(i) printf(" ");
        printf("%d",p[i]);
    }
    printf("\n");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/CC_1012/article/details/88044832