顽强的小白
1086 Tree Traversals Again (25 分)
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.
图片自己脑部
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
题目解析
用栈的形式来表示二叉树,这里就会发现一个有趣的现象,所有入栈的操作序列就是先序遍历,而所有出栈的序列就是中序遍历。发现这个现象后就和上一道二叉树的题目一样了,这次是给出中序和先序求后序遍历。
代码实现
#include <cstdio>
#include <algorithm>
#include <stack>
#include <cstring>
using namespace std;
const int maxn=35;
int n;
int in[maxn];
int pre[maxn];
int post[maxn];
struct node{
int data;
node* l;
node* r;
};
node* create(int inL,int inR,int preL,int preR){
if(inL>inR) return NULL;
node* root=new node;
root->data=pre[preL];
int k;
for(k=inL;k<=inR;++k){
if(in[k]==pre[preL])
break;
}
int left=k-inL;
root->l=create(inL,k-1,preL+1,preL+left);
root->r=create(k+1,inR,preL+left+1,preR);
return root;
}
int cnt=0;
void postOrder(node* root){
if(root==NULL) return;
postOrder(root->l);
postOrder(root->r);
printf("%d",root->data);
cnt++;
if(cnt<n) printf(" ");
}
int main(){
stack<int> s;
scanf("%d",&n);
char mk[6];
int j=0,k=0,x;
for(int i=0;i<n*2;++i){
scanf("%s",mk);
if(strcmp(mk,"Push")==0){
scanf("%d",&x);
pre[j++]=x;
s.push(x);
}else{
in[k++]=s.top();
s.pop();
}
}
node* root=create(0,n-1,0,n-1);
postOrder(root);
return 0;
}