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
--------------------------------------这是题目和解题的分割线--------------------------------------
模拟一下已知中序序列和XX序列求XX序列的思路即可。
#include<cstdio>
#include<queue>
using namespace std;
typedef struct Node
{
int data;
Node *left,*right;
}node;
int post[35],in[35];
//[postL,postR]后序区间,[inL,inR]中序区间
node* create(int postL,int postR,int inL,int inR)
{
//如果序列小于等于0,直接返回
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 numLeft = i - inL;
//左子树的后序区间和中序区间
root->left = create(postL,postL+numLeft-1,inL,inL+numLeft-1);
//右子树的后序区间和中序区间
root->right = create(postL+numLeft,postR-1,i+1,inR);
return root;
}
int n,count = 0;
void levelOrder(node *T)
{
queue<node*> q;
q.push(T);
while(!q.empty())
{
node* top = q.front();
q.pop();
printf("%d",top->data);
if(count!=n-1) printf(" "); //末尾不能输出空格
count++;
if(top->left) q.push(top->left);
if(top->right) q.push(top->right);
}
}
int main()
{
int i;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&post[i]);
for(i=0;i<n;i++)
scanf("%d",&in[i]);
node* T = create(0,n-1,0,n-1);
levelOrder(T);
return 0;
}
460

被折叠的 条评论
为什么被折叠?



