#include<stdio.h>
#include<stdlib.h>
typedef struct csnode
{
int data;
int in;
struct csnode *lchild;
struct csnode *nextsibling;
}CSNode;
CSNode *t,*q;
int preoder()//通过先序遍历的方式输出该树一条从根到叶子的路径
{ //顺便求树的深度
CSNode *stact[1001],*p;
int i,high=-1;
int top=-1;
p=t;
while(p||top!=-1)
{
while(p)
{
top++;
stact[top]=p;
p=p->lchild;
}
if((stact[top]->in)==0)
{
for(i=0;i<=top;i++)
printf("%d ",stact[i]->data);
if(top>high)
high=top;
printf("\n");
}
if(top<0)
break;
else
{
p=stact[top];
top--;
p=p->nextsibling;
}
}
return high;
}
// 创建“孩子-兄弟链表”方式存储的树
int CreatTree( int n)
{
int k,i,j,h; // 父节点编号,子节点编号
t = NULL;
CSNode *queue[1001],*p;
int head,tail;
head=0;
tail=-1;
for(k=1; k<=n;k++)
{
scanf("%d%d",&i,&j);
p=(CSNode*)malloc(sizeof(CSNode)); // 创建结点
p->lchild=NULL;
p->nextsibling=NULL;
p->data=j;
(p->in)=0;
tail++;
queue[tail]=p; //最终 tail+1 为树的总结点的数目
if(i==-1)// 所建为根结点
t=p;//
else // 非根结点的情况
{
for(h=head;h<=tail;h++) //当然这里可以添加条件
//防止 相同的节点的再次出现
if(queue[h]->data==i)
{
queue[h]->in++;
break;
}
q=queue[h];
if (!(q->lchild) ) // 链接第一个孩子结点
q->lchild = p;
// r = p;
else // 链接其它孩子结点
{
q=q->lchild;
while(q->nextsibling)
q=q->nextsibling;
q->nextsibling = p;
}
}
} // for
return tail;
} // CreateTree
int main()
{ //freopen("1.txt","r",stdin);
int high, n;;
scanf("%d",&n);
printf("树一条从根到叶子的路径:\n");
n=CreatTree(n);
high= preoder();
printf("树的深度:%d 树的节点数:%d\n",high+1,n+1);
return 0;
}
/*
n=7
i=fa j
-1 1
1 2
1 3
1 4
3 5
3 6
5 7