一般pat考察树的题目会给出一个数组,数组中的数字将是构造树的元素。根据题目的一些特殊要求,可以构造出这棵树,然后根据题目的输出要求遍历输出这棵树。
pat对树的考察必不可少的就是考察对树的各种遍历
前序遍历 根->左->右
中序遍历 左->根->右
后序遍历 左->右->根
以上三种遍历利用递归或者stack(先进后出)可实现
层序遍历利用queue(先进先出)可实现
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
题目的意思就是由一棵树的后续遍历和中序遍历得出层序遍历。后续遍历的最后一个数是根节点,由这个根节点可以将中序遍历分成左子树和右子树两部分,利用递归的思想再计算左子树和右子树的根节点。最后一步是利用队列的先进先出特性将数组层序遍历的输出。
#include <stdio.h>
#include <vector>
#include <map>
#include <queue>
using namespace std;
struct treeNode
{
int val;
treeNode* left;
treeNode* right;
treeNode()
{
val=-1;
left=NULL;
right=NULL;
}
};
map<int,int> post; //后续遍历相当于一个字典,目录是输入的数据,得到的结果的最大值就是根节点
vector<int> in;
vector<bool> visit;
treeNode* findleaves(vector<int> data);
int main()
{
int n;
scanf("%d",&n);
in.resize(n);
visit.resize(n,false);
for(int i=0;i<n;i++)
{
int a;
scanf("%d",&a);
post[a]=i;
}
for(int i=0;i<n;i++) scanf("%d",&in[i]);
treeNode* root;
root=findleaves(in);
queue<treeNode*> tqe;
tqe.push(root);
printf("%d",tqe.front()->val);
while(!tqe.empty())
{
if(tqe.front()->left!=NULL) tqe.push(tqe.front()->left);
if(tqe.front()->right!=NULL) tqe.push(tqe.front()->right);
tqe.pop();
if(tqe.empty()) break;
if(tqe.front()->val>0) printf(" %d",tqe.front()->val);
}
return 0;