PTA L2-006 树的遍历

原题链接

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
int N;
int post[32];
int in[32];
struct node
{
    int lc;
    int rc;
}Node[32];
int rebuild(int pL,int pR,int iL,int iR)           //后序,中序
{
    if(iL>iR)
        return -1;                                         //无子节点
    int root=post[pR];
    int index=find(in,in+N,root)-in;                       //根节点中序遍历的下标
    int cnt=index-iL;                                      //在当前子序列的下标
    Node[root].lc=rebuild(pL,cnt+pL-1,iL,index-1);         //左子节点
    Node[root].rc=rebuild(cnt+pL,pR-1,index+1,iR);         //右子节点
    return root;
}
void bfs()
{
    queue<int> q;
    int root=post[N-1];
    q.push(root);
    bool space=false;
    while(q.size())
    {
        int val=q.front();
        q.pop();
        if(val>0)
        {
            if(space)
                printf(" ");
            else
                space=true;
            printf("%d",val);

            if(Node[val].lc>0)
               q.push(Node[val].lc);
            if(Node[val].rc>0)
               q.push(Node[val].rc);
        }
    }
}
int main()
{
    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]);
    rebuild(0,N-1,0,N-1);
    bfs();
    return 0;
}
原创文章 39 获赞 5 访问量 4935

猜你喜欢

转载自blog.csdn.net/q1072118803/article/details/85619666