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
总结:
- 本题是根据先序和中序确定一棵树,再用后序序列输出
- 本题先序序列得到是直接用数组存储得到
- 本题的中序序列是用栈和数组得到,碰到pop,记录栈顶元素,然后在数组中记录,把该数弹出
- 因为在输入时,是字符和数字混合输入,但是存在一定的规律性,所以先用strcmp函数比较,分情况讨论
- 熟记根据中序和先序确定一棵树或者中序和后序确定一棵树的办法,有7步,分别是:设立边界(左边界大于右边界)——创建新的结点——给新节点赋值——从中序中找到根结点,分左右树——记录左子树的规模——递归(边界上要注意,首先区间是从0开始的,所以先+中和后+中是不一样的)——返回根结点
- 熟记输出格式,首先先+中+后只是变动printf的顺序,大致分3步:设立边界(root==NULL,return;)——递归(以后序序列的左子树为例:postorder(root->lchild))——输出(位置随着要就的变化而在递归位置的前/中/后)
代码:
#include <stdio.h>
#include <stack>
#include <queue>
#include <string.h>
#include <string>
#include <algorithm>
using namespace std;
stack<int> st;
struct node{
int data;
node* lchild;
node* rchild;
};
queue<node*> q;
int in[50],pre[50];
int total;
node* Create(int preL,int preR,int inL,int inR){
if(preL>preR){ //设立循环边界
return NULL;
}
node* root = new node; //创建一个新的结点
root->data=pre[preL]; //赋值
//在中序遍历中找到根
int k;
for(k=inL;k<inR;k++){
if(root->data==in[k]){
break;
}
}
int numleft=k-inL;
root->lchild=Create(preL+1,preL+numleft,inL,k-1);
root->rchild=Create(preL+numleft+1,preR,k+1,inR);
return root;
}
int acount=0;
void postTraversal(node* root){
if(root==NULL) return;
postTraversal(root->lchild);
postTraversal(root->rchild);
printf("%d",root->data);
acount++;
if(acount<total) printf(" ");
}
int main(){
int pre_acount=0,in_acount=0;
char str[5];
scanf("%d",&total);
for(int i=0;i<2*total;i++){
int x,y;
scanf("%s",str);
if(strcmp(str,"Push")==0){
scanf("%d",&x);
st.push(x);
pre[pre_acount++]=x; //先序序列
}else{
y=st.top();
st.pop();
in[in_acount++]=y;
}
}
node* root=Create(0,total-1,0,total-1);
postTraversal(root);
return 0;
}