#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
using namespace std;
#define Max 100
typedef struct _mtree
{
int data;
int size;
struct _mtree *element[Max];
} mtree;
class queue
{
mtree *a[100];
int size ;
int beg;
public:
queue():size(),beg(){}
void push( mtree* p )
{
if(size >= 100) throw "full";
a[(beg +size)%100] = p;
size++;
}
mtree * top()
{
if(size <= 0 )throw "empty";
return a[beg%100];
}
void pop()
{
if(size<=0)throw "empty";
beg++;
size--;
}
bool empty()
{
return (size==0);
}
};
mtree * searchnode(mtree *root,int data)
{
if(root->data == data) return root;
int i;
//printf("srarchnode root->data = %d\n",root->data);
//printf("srarchnode root->size = %d\n",root->size);
for( i= 0; i<root->size;i++)
{
mtree *result = searchnode(root->element[i],data);
if(result != NULL) return result;
}
return NULL;
}
mtree * BuildTree(char *a,mtree *root)
{
//printf("%s\n",a);
char tmp[Max];
strcpy(tmp,a);
char *tail = tmp;
char * top = tmp;
mtree *childroot= NULL;
int flag = 1;
while(*tail != '\0')
{
if(*tail == ' ')
{
*tail = '\0';
int data = atoi(top);
//printf("data = %d\n",data);
if(flag == 1){
//第一次插入的根节点
if(root == NULL)
{
mtree *p = (mtree*) malloc(sizeof(mtree));
p->data = data;
p->size = 0;
childroot = p;
root = childroot;
//printf("root->data =%d\n",childroot->data);
}
//不然需要先找到那个节点,根据data找
else
{
childroot = searchnode(root,data);
//printf("---childroot->data =%d\n",childroot->data);
//printf("---root->data =%d\n",root->data);
}
flag = 0;
}
else
{
mtree *p = (mtree*) malloc(sizeof(mtree));
p->data = data;
p->size = 0;
childroot->element[childroot->size++] = p;
}
tail++;
top = tail;
}
tail++;
}
int data = atoi(top);
mtree *p = (mtree*) malloc(sizeof(mtree));
p->data = data;
p->size = 0;
childroot->element[childroot->size++] = p;
//printf("data = %d\n",data);
return root;
}
void printtree(mtree* root)
{
queue que;
que.push(root);
while(que.empty() == false)
{
mtree *p = que.top();
printf("%d ",p->data);
que.pop();
for(int i = 0;i<p->size;i++)
{
que.push(p->element[i]);
}
}
printf("\n");
}
int main()
{
char a[Max];
mtree *root = NULL;
while(1)
{
gets(a);
if(strlen(a) <= 3){break;}
root = BuildTree(a,root);
//printf("------------------------------%d\n",root->data);
}
if(root == NULL)
{
printf("root null\n");
}
//printf("------------------------------%d\n",root->data);
printtree(root);
}