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
思路
已知中序、后序,建树,然后用队列层次遍历,保证最后一个不输出空格即可。
Code
#include<iostream>
#include<queue>
using namespace std;
int post[30], in[30];
int n;
struct Tnode{
Tnode* left;
Tnode* right;
int val;
};
/*
根据后序、中序,递归建树
postL:后序序列左边, postR:后序序列右边, inL:中序序列左边, inR中序序列右边:
*/
Tnode* create(int postL, int postR, int inL, int inR){
if(postL > postR)//后序序列长度小于0,递归结束
return NULL;
Tnode* root = new Tnode;//新分配根节点,并赋值
root->val = post[postR];
int k;
for(k=inL; k<=inR; k++)
if(in[k] == root->val)//在中序序列中找到根节点
break;
int leftNum = k - inL;//中序根节点左子树包含节点数
root->left = create(postL, postL+leftNum-1, inL, k-1);
root->right = create(postL+leftNum, postR-1, k+1, inR);
return root;
}
/*层次遍历*/
void layerOrder(Tnode* root){
int num = 0;
queue<Tnode*> q;//注意队列装的是结构体指针,*
q.push(root);
while(!q.empty()){
Tnode* now = q.front();q.pop(); //队首出队
printf("%d", now->val); //访问该节点
if(num++ < n) printf(" ");//保证最后没有空格输出
if(now->left) q.push(now->left);//左子入队
if(now->right) q.push(now->right);//右子入队
}
}
int main(){
cin >> n;
//输入后序,中序
for(int i=0; i<n; i++)
cin >> post[i];
for(int i=0; i<n; i++)
cin >> in[i];
Tnode* root = create(0, n-1, 0, n-1);//建树
layerOrder(root);
return 0;
}