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 (<=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.
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 PopSample Output:
3 4 2 6 5 1
分析:根据题目给出的push,pop操作可以得出前序数组和中序数组,从而可以构建树,然后再进行后序遍历。
(1) 题目中的push操作对应的数组就是前序数组, (1,2,3,4,5,6)
(2) 题目中的pop操作对应的数组就是中序数组,(3,2,4,1,6,5)
(3) 前序数组的第一个元素就是树的根1。而在中序数组中,数字1的左边部分就是以1为根的左子树中的节点,数字1的右边部分就是以1为根的右子树中的节点。
建议参考: http://blog.youkuaiyun.com/solin205/article/details/39157781
正确代码如下:
#include <iostream>
#include <vector>
#include <string>
#include <stack>
using namespace std;
struct Node{
Node *left, *right;
int val;
};
Node * buildTree(int *preorder, int *inorder, int length){
if(length == 0)
return NULL;
int val = preorder[0];
int i, index;
for(i=0; i<length; i++){
if(inorder[i] == val){
index = i;
break;
}
}
Node *N = new Node();
N->val = val;
N->left = buildTree(preorder+1, inorder, index);
N->right = buildTree(preorder+index+1, inorder+index+1, length-index-1);
return N;
}
void buildPostorder(Node *root, vector<int> &postorder){
if(root == NULL)
return;
buildPostorder(root->left, postorder);
buildPostorder(root->right, postorder);
postorder.push_back(root->val);
}
int main(){
int n, i, val;
scanf("%d",&n);
string op;
int preorder[50], inorder[50];
int preIndex=0, inIndex=0;
stack<int> sta;
for(i=0; i<2*n; i++){
cin>>op;
if(op == "Push"){
scanf("%d", &val);
sta.push(val);
preorder[preIndex++] = val;
}else if(op == "Pop"){
inorder[inIndex++] = sta.top();
sta.pop();
}
}
Node *root;
vector<int> postorder;
root = buildTree(preorder, inorder, n);
buildPostorder(root, postorder);
for(i=0; i<postorder.size(); i++){
if(i==0)
printf("%d",postorder[i]);
else
printf(" %d",postorder[i]);
}
printf("\n");
return 0;
}