#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
struct Node{//树节点
int data;
Node *left,*right;
Node():data(0), left(nullptr), right(nullptr){};
};
Node *createTree(int n, int postOrder[], int inOrder[])//递归创建二叉树
{
if(n == 0) return nullptr;
int k(0);
while(postOrder[n-1] != inOrder[k]) ++k;
Node *root = new Node;
root->data = postOrder[n-1];
root->left = createTree(k, postOrder, inOrder);//左子树
root->right = createTree(n - k - 1, postOrder + k, inOrder + k + 1);//右子树
return root;
}
int main()
{
//freopen("in.txt","r",stdin);
int n;
scanf("%d",&n);
int postOrder[35];
int inOrder[35];
for(int i = 0; i < n; ++i){//读取后序遍历的数据
scanf("%d", &postOrder[i]);
}
for(int i = 0; i < n; ++i){//读取中序遍历的数据
scanf("%d", &inOrder[i]);
}
Node *root = createTree(n, postOrder, inOrder);
//层次遍历
queue<Node*> q, next;
q.push(root);
bool first(true);
while(!q.empty()){
while(!q.empty()){
Node *p = q.front();
q.pop();
if(first){
printf("%d", p->data);
first = false;
}
else{
printf(" %d", p->data);
}
if(p->left != nullptr) next.push(p->left);
if(p->right != nullptr) next.push(p->right);
}
std::swap(q, next);
}
return 0;
}
浙大PAT (Advanced Level) Practise 1020 Tree Traversals (25)
最新推荐文章于 2018-02-25 22:39:04 发布