#include<bits/stdc++.h> using namespace std; int n,h[101],z[101]; vector<int>ve; void solve(int hl,int hr,int zl,int zr) { if(hl>hr||zl>zr)return; int i,ki=0; int x=h[hr]; for(i=zl;i<=zr;i++){ if(z[i]==x){ break; } else ki++;//根前面有3个节点 } ve.push_back(x);//根据push放的不同位置,直接得出先后中序,这里先把根放进去,所以先序 solve(hl,hl+ki-1,zl,zl+ki-1); //ve.push_back(x);中序 solve(hl+ki,hr-1,zl+ki+1,zr); //ve.push_back(x);后序 } int main() { int i,j;cin>>n; for(i=0;i<n;i++)cin>>h[i]; for(i=0;i<n;i++)cin>>z[i]; solve(0,n-1,0,n-1); cout<<"Preorder: "; for(i=0;i<ve.size();i++){ if(i!=0)cout<<" "; cout<<ve[i]; } }
推理的博客:https://www.cnblogs.com/liujinghuan/p/5842487.html
已知两种遍历,推层序遍历,要用到结构体,左右节点都用指针;方便输出
#include<bits/stdc++.h> using namespace std; int h[101],z[101],n; struct node{ int data; struct node *l,*r; }; node *build(int l1,int r1,int l2,int r2)//h,z { if(l1>r1||l2>r2)return NULL; node *root=new node; root->data=h[r1]; int i,k=0; for(i=l2;i<=r2;i++){ if(z[i]==h[r1])break; else k++;//左子树有k个节点 } root->l=build(l1,l1+k-1,l2,i-1); root->r=build(l1+k,r1-1,i+1,r2); return root; } void bfs(node *root) { int i; queue<node*>qu; qu.push(root); int k=0; while(!qu.empty()){ node *t=qu.front(); qu.pop(); k++;if(k!=1)printf(" "); printf("%d",t->data); if(t->l!=NULL)qu.push(t->l); if(t->r!=NULL)qu.push(t->r); } } int main(){ int i;scanf("%d",&n); for(i=0;i<n;i++)scanf("%d",&h[i]); for(i=0;i<n;i++)scanf("%d",&z[i]); node *root=build(0,n-1,0,n-1); bfs(root); return 0; }