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
作者: CHEN, Yue
单位: 浙江大学
时间限制: 400 ms
内存限制: 64 MB
代码长度限制: 16 KB
#include <iostream>
#include <vector>
#include<algorithm>
#include <cmath>
#include<map>
#include<cstring>
#include<queue>
#include<string>
#include<set>
using namespace std;
typedef long long ll;
const int maxn=110;
struct node{
int data;
node *lchild,*rchild;
};
int in[maxn],pos[maxn],n;
node* create(int in_l,int in_r,int pos_l,int pos_r){
if(in_l>in_r||pos_l>pos_r) return NULL;
node *root=new node; //链表建立树一定一定不能忘记new node;
root->data=pos[pos_r];
int k;
for(k=in_l;k<=in_r;k++){
if(in[k]==pos[pos_r]) break;
}
int num_left=k-in_l;
root->lchild=create(in_l,k-1,pos_l,pos_l+num_left-1);
root->rchild=create(k+1,in_r,pos_l+num_left,pos_r-1);
return root;
}
void level(node* root){
queue<node*>q; //要加*;
q.push(root);
int i=0;
while(!q.empty()){
node* now=q.front();
if(i!=0) cout<<" ";
cout<<now->data;
if(now->lchild) q.push(now->lchild);
if(now->rchild) q.push(now->rchild);
q.pop();
i++;
}
}
int main(){
cin>>n;
for(int i=0;i<n;i++) cin>>pos[i];for(int i=0;i<n;i++) cin>>in[i];
node *root=create(0,n-1,0,n-1);
level(root);
}

浙公网安备 33010602011771号