Not Only Algorithm,不仅仅是算法,关注数学、算法、数据结构、程序员笔试面试以及一切涉及计算机编程之美的内容 。。
你的位置:NoAlGo博客 » 题解 » 

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

解答

#include <cstdio>
#include <queue>
using namespace std;

int n, post[100], in[100], id;
struct Node { int val, l, r; } node[100]; //静态节点申请

int f(int st1, int ed1, int st2, int ed2)
{
	if (st1 > ed1) return -1;

	int root = id++, i = st2; 
	while (in[i] != post[ed1]) i++;

	node[root].val = post[ed1];
	node[root].l = f(st1, st1+i-1-st2, st2, i-1);
	node[root].r = f(st1+i-st2, ed1-1, i+1, ed2);

	return root;
}

int main()
{
	scanf("%d", &n);
	for (int i = 0; i < n; i++) scanf("%d", post+i);
	for (int i = 0; i < n; i++) scanf("%d", in+i);
	id = 0;
	int root = f(0, n-1, 0, n-1);

	queue<int> q;
	q.push(root);
	bool first = 1;	
	while (!q.empty())
	{
		int fr = q.front(); q.pop();
		if (node[fr].l != -1) q.push(node[fr].l);
		if (node[fr].r != -1) q.push( node[fr].r);
		if (first) { first = 0; }
		else printf(" ");
		printf("%d", node[fr].val);
	}
	printf("\n");
	return 0;
}
上一篇: 下一篇:

我的博客

NoAlGo头像编程这件小事牵扯到太多的知识,很容易知其然而不知其所以然,但真正了不起的程序员对自己程序的每一个字节都了如指掌,要立足基础理论,努力提升自我的专业修养。

站内搜索

最新评论