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
Pop
Sample Output:
3 4 2 6 5 1
题目的意思是通过堆栈模拟得到一颗二叉树,并通过后序遍历输出树的结点,通过堆栈的push pop可以得到这棵树的先序遍历和中序遍历。
#include<iostream>
#include<cstdio>
#include<cmath>
#include<string>
#include "stack"
#include "queue"
using namespace std;
#define maxSize 30
int pre[maxSize],mid[maxSize];
typedef struct TreeNode *Tree;
struct TreeNode {
int value;
Tree left,right;
};
Tree getPost(int *pre, int preStart,int preEnd, int *mid,int midStart,int midEnd){
if(preStart > preEnd || midStart>midEnd){
return NULL;
}
//1、建头结点
Tree root = new TreeNode;
root->value = pre[preStart];
root->left = NULL;
root->right = NULL;
for(int i = midStart;i<=midEnd;i++){
if(mid[i] == pre[preStart]){
root->left = getPost(pre,preStart+1,preStart+i-midStart,mid,midStart,i-1);
root->right = getPost(pre,i-midStart+preStart+1,preEnd,mid,i+1,midEnd);
break;
}
}
return root;
}
void PostOrderTraversal( Tree root ){
if(root == nullptr){
return;
}
PostOrderTraversal(root->left);
PostOrderTraversal(root->right);
//保证行尾没有空格
if(pre[0] == root->value){
printf("%d",root->value);
}else{
printf("%d ",root->value);
}
}
int main(int argc, char *argv[])
{
int num,data,j = 0,k = 0;
stack<int> s;
//读入个数
cin >> num;
for(int i = 0; i < 2 * num; i++){
string str;
cin >> str ;
if(str == "Push"){
cin>> data;
pre[j] = data;
s.push(data);
j++;
}else if(str == "Pop"){
mid[k] = s.top();
s.pop();
k++;
}
}
Tree root = getPost(pre,0,num-1,mid,0,num-1);
PostOrderTraversal(root);
return 0;
}