已知树的先中序遍历--不建树--得到层序遍历

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;


int Count=0;
struct Node
{
    int num;
    int lawyer;
};
Node Floor[20];


bool cmp(struct Node a,struct Node b)
{
    return a.lawyer<b.lawyer;
}


void PreIn_Floor(Node* Pre,Node* In,int len,int lawyer);
void Sort(Node* Floor,int N);


int main()
{


    Node Pre[20],In[20];
    int N;
    cin >> N;
    for(int i=0; i<N; i++)
        scanf("%d",&In[i].num);
    for(int i=0; i<N; i++)
        scanf("%d",&Pre[i].num);


    PreIn_Floor(Pre,In,N,1);


    /* 打印看看排序前是什么结果
    for(int i=0; i<N; i++)
        cout << Floor[i].num << " ";
    cout << endl;
    for(int i=0; i<N; i++)
        cout << Floor[i].lawyer << " " ;
    cout << endl;
    */
        sort(Floor,Floor+N,cmp);
        for(int i=0; i<N; i++)
            cout << Floor[i].num << " " ;


    return 0;
}


void PreIn_Floor(Node* Pre,Node* In,int len,int lawyer)
{
    if( len==0 )//递归的退出条件
        return ;


    int i=-1;
    while( (*Pre).num != In[++i].num ) ;  //思考为什么这样不会是一个死循环,也就是说一定会找到


    Floor[Count].num = (*Pre).num;//每一次递归进行的操作
    Floor[Count].lawyer = lawyer;
    Count++;


    PreIn_Floor( Pre+1,In,i,lawyer+1 );//递归左子树
    PreIn_Floor( Pre+1+i,In+1+i,len-i-1,lawyer+1 );//递归右子树


}
/**


测试样例:
10
1 2 4 8 5 9 10 3 6 7
8 4 2 5 10 9 1 6 3 7
*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值