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




解析

模板题,模板在这PAT && 树

#include<algorithm>
#include<cstdio>
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
vector<int> in, post,layer;
struct node {
	int data;
	node* lchild, *rchild;
	node(int value) :data(value), lchild(nullptr),rchild(nullptr){
	}
};
void change(node*& root,int postL,int postR,int inL,int inR){
	if (postL > postR)
		return;
	root = new node(post[postR]);
	int i = inL;
	while (i != inR) {
		if (in[i] == post[postR])
			break;
		i++;
	}
	int NumLeft = i - inL;
	change(root->lchild, postL, postL + NumLeft - 1, inL, inL + NumLeft - 1);
	change(root->rchild, postL + NumLeft, postR - 1, inL + NumLeft+1, inR);
}
void layerorder(node* root) {
	queue<node*> q;
	q.push(root);
	while (!q.empty()) {
		node* New = q.front();
		q.pop();
		layer.push_back(New->data);
		if (New->lchild != nullptr) q.push(New->lchild);
		if (New->rchild != nullptr) q.push(New->rchild);
	}
}
int main()
{
	int N;
	scanf("%d", &N);
	in.resize(N, 0), post.resize(N, 0);
	for (int i = 0; i < N; i++)
		scanf("%d", &post[i]);
	for (int i = 0; i < N; i++)
		scanf("%d", &in[i]);
	node* root = nullptr;
	change(root, 0, N - 1, 0, N - 1);
	layerorder(root);
	for (int i = 0; i < N; i++)
		printf("%d%c", layer[i], i == N - 1 ? '\n' : ' ');
}

猜你喜欢

转载自blog.csdn.net/weixin_41256413/article/details/84202309
今日推荐