【一只蒟蒻的刷题历程】【PAT】 A1020 树遍历

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


题目大意:

假设二叉树中的所有键都是不同的正整数。 给定后序遍历序列和有序遍历序列,您应该输出相应二叉树的层级遍历序列。

输入规格:

每个输入文件包含一个测试用例。 对于每种情况,第一行给出一个正整数N(≤30),即二叉树中节点的总数。 第二行给出了后顺序,而第三行给出了顺序。 一行中的所有数字都用空格分隔。

输出规格:

对于每个测试用例,在一行中打印相应二叉树的级别顺序遍历序列。 一行中的所有数字必须完全由一个空格分隔,并且行尾不得有多余的空格。

样本输入:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

样本输出:

4 1 6 3 5 7 2


代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
struct node{
	int data;
	node *left,*right;
};
int in[40],post[40];//中序,后序

node *build(int hz,int hy,int zz,int zy) 
//建树(后序左,后右,中左,中右)
{
	if(hz>hy)  //结点数小于等于0
	return NULL;
	node *root = new node;
	root->data = post[hy]; //后序遍历最后一个结点是根节点
	int k;
	for(k=zz;k<=zy;k++) //找到中序遍历中根节点所在位置
	{
		if(in[k] == post[hy])
		break;
	}
	int numleft = k-zz;  //左子树的数量
	root->left = build(hz,hz+numleft-1,zz,k-1);
	root->right = build(hz+numleft,hy-1,k+1,zy);
	return root;
}

void lay(node *root) //层次遍历
{
    queue<node*> q;
	q.push(root);
	vector<int> v;  //为了格式,先放进vector中
	while(q.size())
	{
		node *now = q.front();
		v.push_back(now->data);
		q.pop();
		if(now->left!=NULL) q.push(now->left);
		if(now->right!=NULL) q.push(now->right);
 	}	
 	for(int i=0;i<v.size();i++) //按格式输出
 	{
 		cout<<v[i];
 		if(i<v.size()-1)
 		cout<<" ";
	 }

}
int main() 
{
   int n;
   cin>>n;
   for(int i=0;i<n;i++) //后续
     cin>>post[i];
   for(int i=0;i<n;i++) //中序
     cin>>in[i];
     
    node *root = build(0,n-1,0,n-1); //建树,返回到root中
    lay(root); //层序遍历
    return 0;
}

你可能感兴趣的:(#,二叉树,PTA)