题目描述
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
翻译:一个二叉树中序遍历可以用一个栈非递归实现。举个例子,假设有一棵6节点的二叉树(键值从1到6)。这个栈的操作为:push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop()。根据这些操作队列可以构建一棵特定的二叉树(如图一所示)。你的任务是给出构建的二叉树的后序遍历。
INTUT FORMAT
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.
翻译:每个输入文件包含一组测试数据。对于每组输入数据,第一行包括两个正整数N(<=30),代表一棵树的节点总数(并且假设树的节点为1到N)。接着2N行,每个按照以下格式描述一个栈操作:“Push X”,X为压入栈的节点标号,“Pop”代表出栈的节点编号。
OUTPUT FORMAT
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<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<stack>
#include<algorithm>
#define INF 99999999
using namespace std;
int N;
int pre[40],v[40],in[40],pcount=0,icount=0;
stack<int>s;
int ccount=0,flag=0;
void dfs(int a,int b){
if(a==b){
if(!flag)printf("%d",in[a]),flag=1;
else printf(" %d",in[a]);
ccount++;
return ;
}
if(ccount<N){
int temp=pre[ccount];
ccount++;
if(a<temp)dfs(a,temp-1);
if(b>temp)dfs(temp+1,b);
if(!flag)printf("%d",in[temp]),flag=1;
printf(" %d",in[temp]);
}
}
int main(){
scanf("%d",&N);
int length=N*2;
char Order[10];
int a;
for(int i=0;i<length;i++){
scanf("%s",Order);
switch(Order[1]){
case 'u':{scanf("%d",&a);pre[pcount++]=a;s.push(a);break;}
case 'o':{
int temp=s.top();
s.pop();
v[temp]=icount;
in[icount++]=temp;
break;
}
}
}
for(int i=0;i<N;i++)pre[i]=v[pre[i]];
dfs(0,N-1);
printf("\n");
return 0;
}