复习二叉数 pat l2-006 数的遍历

L2-006. 树的遍历

 

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

输入格式:

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

提交代码

Code Render Status : Rendered By HDOJ C++ Code Render Version 0.01 Beta
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
int hou[31],zhong[31];
struct node
{
     int l,r;//指向数组的元素
}a[70];
int build_tree(int lz,int rz,int lh,int rh)
{
    if(lz>rz) return 0;// 细节处理 对叶子节点的字节点要处理好
    int now,ret=lz;
    now=hou[rh];
  //  cout<<now<<endl;
    while(zhong[ret]!=now) ret++;//根的位置
    int r=rz-ret;//右子树包含节点的个数
    int temp=rh-r;//
    a[now].l=build_tree(lz,ret-1,lh,temp-1);
    a[now].r=build_tree(ret+1,rz,temp,rh-1);
    return now;
}
void print(int x)
{
    queue<int> que;
    que.push(x);
    vector<int> fuck;
    fuck.clear();
    while(!que.empty())
    {
        int temp=que.front();
        que.pop();
        fuck.push_back(temp);
        if(a[temp].l!=0) que.push(a[temp].l);// 脑残忘记加判断
        if(a[temp].r!=0) que.push(a[temp].r);
    }
    cout<<fuck[0];
    for(int i=1;i<fuck.size();i++) cout<<' '<<fuck[i];
    cout<<endl;
}
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++) cin>>hou[i];
    for(int i=1;i<=n;i++) cin>>zhong[i];
    int root;
    root=build_tree(1,n,1,n);
    print(hou[n]);
    return 0;
}
原文地址:https://www.cnblogs.com/z1141000271/p/6541607.html