1020 Tree Traversals分数 25
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
//已知后序post和中序in,输出层序level
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
struct node{
int data;
node* lchild;
node* rchild;
};
int pre[50],in[50],post[50];
int n;
//先建树
//1.左边序号比右边大,不符合 2.先定义根为一个新节点,根据后序左右根找到根 3.在中序中找到根 确定左子树和右子树
//4.根据左子树和右子树的长度相等,确定后续中的左右子树 5.最后返回根节点
//后序 左右根 2315764 4为根
node* create(int postl,int postr,int inl,int inr){
if(postl>postr)return NULL;
node* root = new node;
root->data=postr;
for(int i=inl;i<=inr;i++){
if(in[i]==post[postr])break;
}
int numleft=i-inl; //左子树个数,!!! i为根节点序号
root->lchild=create(postl,postl+numleft-1,inl,i-1);
int numright=inr-i;//右子树个数
root->rchild=create(postl+numleft,postr,i+1,inr);
return root;
}
//层序遍历用到的是队列
int num=0;//输出数字的个数
void bfs(node* root){
queue<node*> q;//队列里是存地址
q.push(root);
while(!q.empty()){
node* now=q.front();
q.pop();
printf("%d",now->data);
num++;
if(num<n)printf(" ");
if(now->lchild!=NULL)q.push(now->lchild);
if(now->rchild!=NULL)q.push(now->rchild);
}
}
int main(){
int i;
cin>>n;
for(i=0;i<n;i++){
cin>>post[i];
}
for(i=0;i<n;i++){
cin>>in[i];
}
node* root = create(0,n-1,0,n-1);
bfs(root);
}