pta甲级 43 Tree Traversals Again

来源:互联网 发布:大淘客cms二级域名 编辑:程序博客网 时间:2024/06/13 11:44

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.


Figure 1

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer NN (\le 3030) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to NN). Then 2N2N 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:

6Push 1Push 2Push 3PopPopPush 4PopPopPush 5Push 6PopPop

Sample Output:

3 4 2 6 5 1
 
  • 时间限制:400ms
  • 内存限制:64MB
  • 代码长度限制:16kB
  • 判题程序:系统默认
  • 作者:陈越
  • 单位:浙江大学
 

给了一堆条件,其实本质上很简单。根据题目所说的,pop的值正好是一个中序遍历

观察一下不难发现,根据之前文章(树遍历的非递归写法http://blog.csdn.net/sentimental_dog/article/details/52821853),很容易明白其实push的过程就是一个先序遍历

所以,这题就转化成了由先序遍历和中序遍历求后序遍历

代码就不写了,关于树的遍历方式转化可以看我上一篇博文(二叉树便利方法的转化http://blog.csdn.net/sentimental_dog/article/details/52823343)


0 0