树的遍历
我们知道树的遍历分为三种情况,前序,中序,后序,层序遍历
我们现在要讨论的问题是得知前序和中序,求得后序和层序遍历
或者得知后序和中序,求得前序和层序遍历
得知后序和中序,计算层序
#include<iostream>
#include <cstdio>
#include <set>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn=40;
int hou[maxn];
int mid[maxn];
struct node{
int le;
int ri;
}tree[maxn];
int dfs(int ma,int mb,int ha,int hb){
// if(ma==0||mb==0||ha==0||hb==0)return 0;
if(ma>mb)return 0;
int root=hou[hb];
int p1=ma;
int p2;
while(mid[p1]!=root)p1++;
p2=p1-ma;
tree[root].le=dfs(ma,ma+p2-1,ha,ha+p2-1);
tree[root].ri=dfs(p1+1,mb,ha+p2,hb-1);
return root;
}
void bfs(int root){
queue<int>q;
q.push(root);
while(!q.empty()){
int cur=q.front();
q.pop();
if(cur!=root)cout<<" ";
cout<<cur;
int le,ri;
le=tree[cur].le;
ri=tree[cur].ri;
if(le)q.push(le);
if(ri)q.push(ri);
}
}
int main ()
{
int n;
while(cin>>n){
for(int i=0;i<=n;i++){
tree[i].le=0;
tree[i].ri=0;
}
for(int i=0;i<n;i++)cin>>hou[i];
for(int i=0;i<n;i++)cin>>mid[i];
int root=dfs(0,n-1,0,n-1);
bfs(root);
}
return 0;
}
得知前序和中序,求得层序和这个类似。