【一隻蒟蒻的刷題歷程】【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 <iostream>
#include <algorithm>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <set>
#include <map>
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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章