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 N (≤) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2 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
push的顺序实际上是前序遍历序列,而pop的顺序实际上是中序遍历序列,通过这两个序列可以确定树,但比较麻烦。所以可以根据中序遍历的特点来建树。pop之后的push是右子树结点,连续的push是左子树结点,所以可以设立一个变量status来判断是左子树还是右子树,连续的pop中最后一次pop先不弹栈,因为接下来的push是根结点的右子树。
代码:
#include <stdio.h> #include <string.h> struct tree { int left,right; }s[31]; int flag = 0; void postorder(int t) { if(t == -1)return; postorder(s[t].left); postorder(s[t].right); if(!flag) { flag = 1; printf("%d",t); } else printf(" %d",t); } int sta[31],no = 0; int main() { char op[5]; int n,d,root = -1; scanf("%d",&n); for(int i = 0;i < n;i ++) { s[i + 1].left = s[i + 1].right = -1; } int status = 0;///代表状态,0表示是树根,1表示是栈顶元素的左子树,2表示是栈顶元素的右子树,这个时候要将栈顶元素弹出。 for(int i = 0;i < n * 2;i ++) { scanf("%s",op); if(strcmp(op,"Push") == 0) { scanf("%d",&d); if(status == 1) { s[sta[no - 1]].left = d; sta[no ++] = d;//这里不是no ++,因为栈顶元素是早就该出栈却特意保留的。 } else if(status == 2) { s[sta[no - 1]].right = d; sta[no - 1] = d; status = 1; } else { root = d; status = 1; sta[no ++] = d; } } else { if(status == 1) status = 2; else no --; } } postorder(root); }