PAT 1020 Tree Traversals
最近在学数据结构二叉树,找到PAT上关于二叉树的题做了一下。先看题:
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<bits/stdc++.h>
using namespace std;
int ans[10000] = {0};
map<int,int> inordermp;
int postorder[10000];
int inorder[10000];
void create(int num,int post_left,int post_right,int in_left,int in_right,int postorder[],int inorder[],map<int,int> inordermp){
if(post_left>post_right) return;
ans[num] = postorder[post_right];
int mid = inordermp[postorder[post_right]];
int left = mid-in_left;
int right = in_right-mid;
create(2*num,post_left,post_left+left-1,in_left,mid-1,postorder,inorder,inordermp);
create(2*num+1,post_right-right,post_right-1,mid+1,in_right,postorder,inorder,inordermp);
}
int main(){
int n;
cin>>n;
for(int i = 0;i<n;i++){
scanf("%d",&postorder[i]);
}
for(int i = 0;i<n;i++){
scanf("%d",&inorder[i]);
}
for(int i = 0;i<n;i++){
inordermp[inorder[i]] = i;
}
int post_left = 0,post_right = n-1,in_left = 0,in_right = n-1;
create(1,post_left,post_right,in_left,in_right,postorder,inorder,inordermp);
int t = 0;
for(int i = 0;i<10000;i++){
if(ans[i]!=0) {cout<<ans[i];t++;
if(t!=n) cout<<" ";}
}
cout<<endl;
return 0;
}