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
#include <stdio.h> #include <string.h> void ReadTree(int Pre[], int In[], int N); void GetPost(int Pre[], int In[], int Post[], int preL, int inL, int postL, int N); int main(){ int N; scanf("%d",&N); int flag = 0,Pre[30]={0},In[30]={0},Post[30]={0}; ReadTree(Pre, In, N); GetPost(Pre, In, Post, 0, 0, 0 ,N); for (int i = 0; i < N; ++i) { if(!flag) {printf("%d",Post[i]); flag++; } else printf(" %d",Post[i]); } return 0; } void ReadTree(int Pre[], int In[], int N){ int tail1=0,tail2=0, flag=0, A[30]={0}; int Stack[30]={0}; char op[4]; for(int i = 0; i< 2*N ; i++){ scanf("%s",&op); if( ! strcmp(op,"Push")) { scanf("%d",&Stack[flag]); //构造前序遍历数组 Pre[tail1++] = Stack[flag]; flag++; } else In[tail2++] = Stack[--flag]; //构造中序遍历数组 } } void GetPost(int Pre[], int In[], int Post[], int preL, int inL, int postL, int N) { if (N == 0) return ; if (N == 1) { Post[postL] = Pre[preL]; return ; } int root = Pre[preL]; Post[postL + N - 1] = root; //在中序遍历数组上找出root的位置 int i = 0; while (i < N) { if (In[inL + i] == root) break; ++i; } // 计算出root节点左右子树节点的个数 int L = i, R = N - i - 1; // 递归的进行求解 GetPost(Pre, In , Post, preL + 1, inL, postL, L); GetPost(Pre, In, Post, preL + L + 1, inL + L + 1, postL + L, R); }
总结:
1.入栈顺序即为前序遍历,出栈顺序为中序遍历
2. 先读入并存储前序遍历数组和中序遍历数组,然后求后序遍历
3. 前序第一个值即为Root,也是后序数组最后一个值,同时Root将中序数组分割为左子树和右子树。 然后递归求解左子树和右子树。
对于Sample的求解结果为:
刚开始时,前序遍历的第一个元素1肯定是该二叉树的根节点,因此为postOrder的最后一个元素,在中序遍历中1前面的元素肯定为该颗二叉树的左子树在1右边的元素肯定为该二叉树的右子树,因此,递归的求解该二叉树。
参考资料:https://blog.csdn.net/shinanhualiu/article/details/49279051