题目:http://pta.patest.cn/pta/test/16/exam/4/question/667
PTA - Data Structures and Algorithms (English) - 5-5
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.
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.
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.
解法转自:http://www.cnblogs.com/clevercong/p/4177802.html
动态的“添加结点”并遍历过程,不需要建树。
借助“栈”进行树的后续遍历;( times:可由此栈操作判断中当前结点有左子树还是右子树中 )
每次PUSH,times = 1;// PUSH:可看作访问左孩子
每次POP检查栈顶记录的times:
- 如果是1,弹出来变成2压回栈;// POP:可看作由左孩子转到访问右孩子
- 如果是2,则弹出,放入存放结果的vector中,重复这一过程,直到栈顶times为1。// POP:可看作访问根节点
所有PUSH与POP操作执行完毕时,输出vector内的数据和stack中的数据。 注意要处理最后的空格。
注:此方法可推广到n叉树,只需改变times的值即可。
……
转载于:https://www.cnblogs.com/claremore/p/4806304.html