光从前序表示,不能构造出唯一的树,但是加上了层号表示就可以了。下面是代码具体实现
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <fstream>
#include <istream>
#include <ostream>
#include <complex>
#include <cstring>
#include <utility>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <string>
#include <cctype>
#include <ctime>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <new>
#include <set>
#include <map>
using namespace std;
const int maxn = 30;
const int INF = 0x3f3f3f3f;
struct Dnode
{
char data;
int level;
};
struct Node
{
char data;
int level;
Node *child[maxn];
Node *parent;
Node(Dnode a)
{
data = a.data;
level = a.level;
for (int i=0; i<maxn; i++)
child[i] = NULL;
parent = NULL;
}
};
Dnode a[maxn];
Node* build_tree(Dnode *a, int n)
{
Node *root, *p, *q;
if (n < 1) return NULL;
root = new Node(a[0]);
p = root;
for (int i=1; i<n; i++)
{
q = new Node(a[i]);
while (p->level >= q->level)
p = p->parent;
q->parent = p;
int j = -1;
while (p->child[++j] != NULL);
p->child[j] = q;
p = q;
}
return root;
}
void postorder(Node *root)
{
if (root)
{
for (int i=0; i<maxn; i++)
{
if (root->child[i])
postorder(root->child[i]);
else break;
}
printf("%c", root->data);
}
}
int main()
{
//freopen("1.txt", "r", stdin);
int n;
scanf("%d", &n);
getchar();
for (int i=0; i<n; i++)
{
scanf("(%d,%c)", &a[i].level, &a[i].data);
getchar();
}
Node *root = build_tree(a, n);
postorder(root);
putchar('\n');
return 0;
}