#include<stdio.h> //Level-order sequence with degree(森林的带度数层次序列存储)
#include<string.h>
#include<stdlib.h> //算法思想:利用队列存储输入的带度数的层次遍历序列,从队首开始遍历队列,
#define MAX 100 //根据结点度数的不同进行相应的处理
int N; //The number of trees
int LEN[MAX];
typedef struct node
{
char info;
int degree;
struct node *firstchild, *nextsibling;
}BT;
BT *transform(BT *Node[],int i) //Create the Binary Tree from the level-order sequence with degree,return the root
{
int front = 0, rear = 0, deg;
BT *p, *q;
Node[rear++]->nextsibling = NULL;
while (rear < LEN[i])
{
p = Node[front++];
deg = p->degree;
if (deg == 0)
{
p->firstchild = NULL; //叶子结点,将左指向NULL
}
else
{ //非终端结点
deg--;
q = Node[rear++];
p->firstchild = q; //先向左,再向右
while (deg--)
{
q->nextsibling = Node[rear++]; //兄弟结点
q = q->nextsibling;
}
q->nextsibling = NULL; //最右的兄弟结点的右指向NULL
}
}
while (front < rear) //将front之后的叶子结点的左指向NULL
{
Node[front]->firstchild = NULL;
front++;
}
return Node[0]; //返回转化后的二叉树的根结点(此时根的右为空)
}
void inorder(BT *T) //Inorder Traverse
{
if (!T) return;
inorder(T->firstchild);
printf("%c ", T->info);
inorder(T->nextsibling);
}
int main()
{
int i, j;
BT *Node[MAX];
BT *Root[MAX];
char c;
scanf("%d", &N);
c = getchar(); //Storage Enter(!!!必须要有,否则出错)
for (i = 0; i < N; i++)
{
j = 0;
do
{
Node[j] = (BT *)malloc(sizeof(BT));
c = getchar(); //Storage the info
Node[j]->info = c;
c = getchar(); //Storage the blank
scanf("%d", &Node[j]->degree);
j++;
c = getchar(); //Storage the blank or Enter,when Enter,stop
}while (c == ' ');
LEN[i] = j; //Storage the number of node of each tree
Root[i] = transform(Node, i);
}
for (i = 0; i < N - 1; i++)
Root[i]->nextsibling = Root[i + 1]; //将N棵树的根节点链接起来
inorder(Root[0]); //Root[0]即为转换后二叉树的根节点
printf("\n");
return 0;
}