
Figure 1
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.
6 Push 1 Push 2 Push 3 Pop Pop Push 4 Pop Pop Push 5 Push 6 Pop Pop
3 4 2 6 5 1
step one: 首先根据输入,构造出原树的结构。
step two: 后序遍历原树。
关于第一步,需要观察Push和Pop,找出构造原树的方法:
每次Push相当于插入节点,Pop相当于回朔,为了便于回朔的实现,根据最后Pop出的节点的 Id,从已经构造的原树中查找应该回朔到的节点。
关于第二步,如果有n个节点,需要输出n-1个空格,经过观察发现,打印每个节点时,后面跟一个空格,根节点除外,这样就可以打印符合要求的结果,所以只需要能判断是否为根节点即可。
代码如下: