考察后序、中序序列递归地还原二叉树,层次遍历。比较基础。
#include <cstdio>
#include <queue>
using namespace std;
struct node{
int data;
node *left, *right;
};
int N;
int post[30], in[30];
//根据后序、中序序列构造二叉树,返回根结点指针
node* create_tree(int postL, int postR, int inL, int inR);
//层次遍历,输出结点
void level_trav(node *root);
int main(){
scanf("%d", &N);
for(int i=0; i<N; i++) scanf("%d", &post[i]);
for(int i=0; i<N; i++) scanf("%d", &in[i]);
node *root = create_tree(0, N-1, 0, N-1);
level_trav(root);
return 0;
}
node* create_tree(int postL, int postR, int inL, int inR){
if(postL>postR) return NULL;
node *root = new node;
root->data = post[postR];
int i;
for(i=inL; i<=inR; i++){
if(in[i]==root->data) break;
}
int left_len = i - inL;
root->left = create_tree(postL, postL+left_len-1, inL, i-1);
root->right = create_tree(postL+left_len, postR-1, i+1, inR);
return root;
}
void level_trav(node *root){
queue<node*> q;
if(root==NULL) return;
q.push(root);
int print_ct=0;
while(!q.empty()){
node *n = q.front();
q.pop();
printf("%d", n->data);
if(++print_ct<N) printf(" ");
if(n->left!=NULL) q.push(n->left);
if(n->right!=NULL) q.push(n->right);
}
return;
}