题目描述:https://www.patest.cn/contests/pat-a-practise/1086
提交情况:
代码:
#include <iostream> #include <string> #include <vector> #include <malloc.h> using namespace std; #define N 33 #define INF 0x3f3f3f3f int number[N],top = -1,count,n; vector<int> num; typedef struct BTree { int data; struct BTree* leftTree; struct BTree* rightTree; }BTree; //建立二叉树 BTree* creat() { if( number[count] == INF ) //直接返回空 return NULL; else { BTree* root = (BTree*)malloc(sizeof(BTree)); root->data = number[count]; count++; root->leftTree = creat(); count++; root->rightTree = creat(); return root; } } void postOrder( BTree* bt ) { if( bt ) { postOrder(bt->leftTree); postOrder(bt->rightTree); num.push_back(bt->data); } } int main () { cin>>n; //控制输入格式,把输入的节点信息存储在number中,若左右子树为空,则赋值为INF。 //以前遇到过类似的题目,转换为以前的题目的情况 for( int i=1;i<=2*n;++i ) { string str; int num; cin>>str; if( str == "Push" ) { scanf("%d",&num); number[++top] = num; } else if( str == "Pop" ) { number[++top] = INF; } } number[++top] = INF; //最后多赋值一个,建立二叉树时方便返回。 count = 0; BTree *root = creat(); postOrder(root); for( int i=0;i<num.size();++i ) { if( i == num.size()-1 ) cout<<num[i]<<endl; else cout<<num[i]<<" "; } return 0; }