题目地址:http://www.patest.cn/contests/mooc-ds2015spring/03-树2
这道题陈越老师的解法太赞了。
push进去的数字序列就是前序,而pop()出来的序列就是后序,so...剩下的我就不说了,
前序中序求后续是很经典的递归,如果不清楚可以百度一下~
我这道题的解法是通过找规律建树,囧。
规律就是:
在push时,看一看上一个操作是不是push,如果是,则插到上一个数左边。
如果不是,则插入到上一次pop()出来的右边。
#include<stdio.h>
#include<stack>
using namespace std;
typedef struct node{
int left,right;
int x;
bool pop;
}Tree;
Tree tree[31];
stack<int> S;
int coun;
void postOrder(int root){
if(tree[root].left!=-1)
postOrder(tree[root].left);
if(tree[root].right!=-1)
postOrder(tree[root].right);
if(coun==0){
printf("%d",tree[root].x);
coun++;
}
else{
printf(" %d",tree[root].x);
coun++;
}
}
int main(){
coun=0;
bool push = true;
char str[10];
int i,N,x,out,root;
for(i=0;i<31;i++){
tree[i].x=i;
tree[i].left=tree[i].right=-1;
tree[i].pop=false;
}
scanf("%d",&N);
//gets(str);
//主代码:
for(i=0;i<2*N;i++){
scanf("%s",str);
if(i==0){
scanf("%d",&x);
root=x;
S.push(x);
continue;
}
if(str[1]=='u'){
scanf("%d",&x);
if(push){
tree[S.top()].left=x;
S.push(x);
//“上一次”操作的是push
push=true;
}
else{
tree[out].right=x;
S.push(x);
//“上一次”操作的是push
push=true;
}
}
else if(str[1]=='o'){
out=S.top();
S.pop();
//上一次操作的是pop();
push=false;
}
}
postOrder(root);
return 0;
}