思想很简单,输入的字符串序列是一个递归的
//左右链表示
#include <iostream>
using namespace std;
#define N 30
char Data[2*N][10];
int counter;
typedef int Elemtype_Tree;
struct Tree_Data
{
Tree_Data* lchild;
Tree_Data* rchild;
Elemtype_Tree data;
int Status; //保留断点
Tree_Data* temp;
};
typedef Tree_Data* BTREE;
typedef BTREE ElementType;
int temp[2 * N];
void PostOrder(int temp[2 * N],BTREE BT)
{
if (BT != NULL)
{
PostOrder(temp,BT->lchild);
PostOrder(temp,BT->rchild);
temp[counter++] = BT->data;
}
}
int SearchPop(int n, int from) //n是树中结点个数,from是Push所在结点对应的数组行下标从0开始
{
int push = 0;
int pop = 0;
int i;
for ( i = from+1; i < 2*n-1; i++)
{
if (Data[i][1] == 'u') push++;
else pop++;
if (pop > push) break;
}
return i;
}
int chartoint(char *p)
{
if (*(p + 1) == 0) return (*p) - '0';
return (*p - '0') * 10 + (*(p + 1) - '0');
}
BTREE Creat(char Data[2 * N][10],int From,int To,int n) //生成二叉树
{
if (To > 2*n - 1 || From < 0 || To <= From||n == 0) return NULL;
BTREE root = (BTREE)calloc(1, sizeof(Tree_Data));
char* p = &Data[From][5];
root->data = chartoint(p);
int q = SearchPop(n, From);
if (From + 1 == q) root->lchild = NULL;
else root->lchild = Creat(Data, From+1,q-1,n);
if(q==To) root->rchild = NULL;
else root->rchild = Creat(Data, q+1, To,n);
return root;
}
int main()
{
for (int i = 0; i < 60; i++)
{
for (int j = 0; j < 10; j++)
Data[i][j] = 0;
}
int n;
cin >> n;
getchar();
for (int i = 0; i < 2*n; i++)
{
//scanf_s("%[^\n]", Data[i],10);
int j = 0;
while (1)
{
char temp = getchar();
if (temp == '\n') break;
else Data[i][j++] = temp;
}
}
BTREE root = Creat(Data, 0, 2 * n-1, n);
PostOrder(temp,root);
for (int i = 0; i < counter; i++)
{
if (i == counter - 1) printf("%d", temp[i]);
else printf("%d ", temp[i]);
}
}