您的位置:首页 > 其它

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

2016-06-22 10:24 351 查看
#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
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: