PAT甲级-1020 Tree Traversals(25 分)【后序中序+层序遍历】

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

解题思路:将中序,后序转化成前序,并多加了一个参数,index,左子树就2*index+1,右就2*index+2,先将其赋值为-1,嘴笨,还是代码比较清楚。

#include<bits/stdc++.h>
using namespace std;
vector<int>pos,in,level(100000,-1);
void pre(int root,int start,int end,int index)
{
	if(start>end) return ;
	int i=start;
	while(i<end&&in[i]!=pos[root]) i++;
	level[index]=pos[root];
	pre(root-(end-i+1),start,i-1,2*index+1);
	pre(root-1,i+1,end,2*index+2);
}
int main(void)
{
	int n,flag=0;
	scanf("%d",&n);
	pos.resize(n);
	in.resize(n);
	for(int i=0;i<n;i++) scanf("%d",&pos[i]);
	for(int i=0;i<n;i++) scanf("%d",&in[i]);
	int i=0;
	pre(n-1,0,n-1,0);
	for(int i=0;i<level.size();i++)
	{
		if(level[i]!=-1) 
		{
			if(flag!=0) printf(" ");
			printf("%d",level[i]);
		}
		flag++;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Imagirl1/article/details/82178848