PAT 1020 Tree Traversals (后序中序求层序)

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

思路

已知后序遍历、中序遍历的序列,求层序遍历。

用一个队列,每次取出一个元素,把后序遍历的最后一个元素输出,然后将此元素在中序序列中的左半部分入队,右半部分入队。

每次入队前,检查下长度是否合法(是否大于0)。

(还是讨厌读大段大段的英文。。。

代码

#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <string.h>
#include <algorithm>
#include <cmath>
#include <map>
#include <queue>
#include <stack>
#include <functional>
#include <limits.h> 
using namespace std;
int a[40], b[40];
struct node{
	int s1, e1; // 后序序列的始末 
	int s2, e2; // 中序序列的始末 
	node(){
	}
	node(int _s1, int _e1, int _s2, int _e2){
		s1 = _s1;		e1 = _e1;		
		s2 = _s2;		e2 = _e2;
	}
};

int main() {
	int N;
	cin >> N;
	for(int i = 0; i < N; i++){		cin >> a[i];	}
	for(int i = 0; i < N; i++){		cin >> b[i];	}
	queue<node> mq;
	mq.push(node(0, N - 1, 0, N - 1));
	int flag = 0;
	while(!mq.empty()){
		node t = mq.front();
		int s1 = t.s1, e1 = t.e1, s2 = t.s2, e2 = t.e2;
		//cout << s1 << " " << e1 << " " << s2 << " " << e2 << endl;
		mq.pop();
		if(flag)	cout << " ";
		flag = 1;
		cout << a[e1] ;
		if(e1 == s1)	continue;
		int pos = s2;
		while(b[pos] != a[e1]){	pos++; }
		int len = pos - s2;	//左子树遍历长度 
		if(len)		mq.push(node(s1, s1 + len - 1, s2, s2 + len - 1));
		len = e2 - pos;	//右子树遍历长度 
		if(len)		mq.push(node(e1 - len, e1 - 1, pos + 1, pos + len));
	}
	return 0; 
}

posted @ 2020-03-03 20:49  阳离子  阅读(142)  评论(0编辑  收藏  举报