标签:root c++ oid pos mat class name push 结果
链接
给定后序和中序,求层序结果
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
node *lchild;
node *rchild;
};
const int maxn = 100;
int post[maxn], in[maxn];
node *create(int postL, int postR, int inL, int inR){
if(postL > postR) return NULL;
int k;
for(k=inL;k<=inR;k++){
if(in[k] == post[postR]) break;
}
int cnt = k-inL;
node *root = new node;
root->data = post[postR];
root->lchild = create(postL, postL+cnt-1, inL, k-1);
root->rchild = create(postL+cnt, postR-1, k+1, inR);
return root;
}
vector<int> ans;
void layerOrder(node *root){
queue<node*> q;
q.push(root);
while(!q.empty()){
node *now = q.front();
ans.push_back(now->data);
q.pop();
if(now->lchild) q.push(now->lchild);
if(now->rchild) q.push(now->rchild);
}
}
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>post[i];
}
for(int i=0;i<n;i++){
cin>>in[i];
}
node *root = create(0, n-1, 0, n-1);
layerOrder(root);
for(int i=0;i<ans.size();i++){
if(i==0) cout<<ans[i];
else cout<<" "<<ans[i];
}
cout<<endl;
}
PAT A1020 Tree Traversals [二叉树遍历]
标签:root c++ oid pos mat class name push 结果
原文地址:https://www.cnblogs.com/doragd/p/11266568.html