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

PAT 1086. Tree Traversals Again

An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.

Input Specification

Each input file contains one test case. For each case, the first line contains a positive integer N (<=30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: "Push X" where X is the index of the node being pushed onto the stack; or "Pop" meaning to pop one node from the stack.

Output Specification

For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input

6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop

Sample Output

3 4 2 6 5 1

解答

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

struct Node 
{
	int val, l, r;
	Node () : val(0), l(-1), r(-1) {}
} node[100];

bool flag = 1;
void post(int x)
{
	if (node[x].l != -1) post(node[x].l);
	if (node[x].r != -1) post(node[x].r);
	if (flag) flag = 0;
	else printf(" ");
	printf("%d", node[x].val);	
}

int main()
{
	int n, id = 0; scanf("%d", &n);

	stack<int> s;
	for (int i = 0, preop = 0, preid = -1; i < 2 * n; i++)
	{
		char op[10]; scanf("%s", op);
		if (op[1] == 'o')
		{
			preop = 1, preid = s.top();	s.pop();			
		}
		else
		{
			scanf("%d", &node[id].val);
			if (preid != -1)
				if (preop) node[preid].r = id;
				else node[preid].l = id;
			s.push(id);
			preop = 0, preid = id;
			id++;
		}
	}

	post(0);
	printf("\n");

	return 0;
}
上一篇: 下一篇:

我的博客

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

站内搜索

最新评论