☀L2-006 树的遍历 (25分)[PTA][后序遍历+中序遍历==》层序遍历]

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数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

------------------------------------------

建树 

void rec(int L,int R,int n)

{

    if(L>=R)

        return;

    T[n].value=post[pos--];

    T[n].left=2*n;

    T[n].right=2*n+1;

    int mid;

    for(mid=L;mid<R;mid++)

    {

        if(in[mid]==T[n].value)//找到根结点在中序遍历中的位置

        {

            break;

        }

    }

根结点右边是右子树

    rec(mid+1,R,2*n+1);//建立右子树

根结点左边是左子树

    rec(L,mid,2*n);//建立左子树

}

-------------------------------------------

层次遍历

void bfs()

{

    queue<int>q;

    q.push(1);//根结点序号

    while (!q.empty())

    {

        node cur=T[q.front()];//当前结点

        q.pop();//当前结点出栈

        if(indx==1)

        {

            cout<<cur.value;

            indx++;

        }

        else

        {

            cout<<" "<<cur.value;

        }

        if(T[cur.left].value!=-1)

            q.push(cur.left);//左子树结点序号入栈

        if(T[cur.right].value!=-1)

            q.push(cur.right);//右子树结点序号入栈

    }

}

 

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<set>
#include<queue>
#include<stack>
using namespace std;
const int maxn = 10000;

int post[maxn],in[maxn];

struct node
{
    int value,left,right;
}T[maxn];

int pos;

void rec(int L,int R,int n)
{
    if(L>=R)
        return;
    T[n].value=post[pos--];
    T[n].left=2*n;
    T[n].right=2*n+1;
    int mid;
    for(mid=L;mid<R;mid++)
    {
        if(in[mid]==T[n].value)
        {
            break;
        }
    }
    rec(mid+1,R,2*n+1);//建立右子树
    rec(L,mid,2*n);//建立左子树
}

int indx=1;

void bfs()
{
    queue<int>q;
    q.push(1);
    while (!q.empty())
    {
        node cur=T[q.front()];
        q.pop();
        if(indx==1)
        {
            cout<<cur.value;
            indx++;
        }
        else
        {
            cout<<" "<<cur.value;
        }
        if(T[cur.left].value!=-1)
            q.push(cur.left);
        if(T[cur.right].value!=-1)
            q.push(cur.right);
    }
}

int main()
{
    int N;
    cin>>N;
    for(int i=0;i<N;i++)
    {
        cin>>post[i];
    }
    for(int i=0;i<N;i++)
    {
        cin>>in[i];
    }
    memset(T,-1,sizeof(T));
    pos=N-1;
    rec(0,N,1);
    bfs();//层序遍历
    return 0;
}

 参考:https://blog.csdn.net/a1097304791/article/details/88830892?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522160635078519726885864834%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=160635078519726885864834&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~sobaiduend~default-3-88830892.pc_v1_rank_blog_v1&utm_term=L2-006+树的遍历++25分&spm=1018.2118.3001.4450

猜你喜欢

转载自blog.csdn.net/qq_43660826/article/details/110160871