Description
以二元组(father,child)的形式自上而下、自左而右依次输入树的各边,建立树的child-sibling链表,并输出该树的先根遍历序列、后根遍历序列、树的高度以及叶子结点数。
Input
第一行输入一个整数n,然后后面n行
输出所建立的树的先根遍历学列、后根遍历序列、高度以及叶子结点数。
Sample Input
7
A B
A C
A D
C E
C F
E G
Sample Output
PreOrder: A B C E G F D
PostOrder: B G E F C D A
Depth:4
Number of leaves:4
运行得出来,但是oj上显示 runtime error
代码如下
```c
#include <iostream>
#include <stdio.h>
#include <cstdio>
#include <stdlib.h>
#define MAXSIZE 10000
using namespace std;
typedef struct CSNode
{
int data;
struct CSNode *firstchild,*nextsibling;
}CSNode,*CSTree;
int CreateCSTree(CSTree &T)
{
char input[2];
int n,i;
CSTree queue[MAXSIZE];
int front,rear;
CSTree p,q;
scanf("%d%*c",&n);
front=rear=0;
for(i=0;i<n;i++)
{
scanf("%c%*c%c%*c",&input[0],&input[1]);
p=(CS)malloc(sizeof(CSNode));
p->data=input[1];
p->firstchild=p->nextsibling=NULL;
queue[rear]=p;
rear=(rear+1)%MAXSIZE;
if(input[0]=='#') T=p;
else
{
for(q=queue[front];q->data!=input[0];)
{
front=(front+1)%MAXSIZE;
q=queue[front];
}
if(!q->firstchild) q->firstchild=p;
else
{
for(q=q->firstchild;q->nextsibling;q=q->nextsibling);
q->nextsibling=p;
}
}
}
return 0;
}
//
void PreOrderTraverse(CSTree T)
{
if(T)
{
printf("%c ",T->data);
PreOrderTraverse(T->firstchild);
PreOrderTraverse(T->nextsibling);
}
}
//
void PostOrderTraverse(CSTree T)
{
if(T)
{
PostOrderTraverse(T->firstchild);
printf("%c ",T->data);
PostOrderTraverse(T->nextsibling);
}
}
//
int depth(CSTree T)
{
int max,d;
CSTree p;
if(!T) return 0;
else
{
for(max=0,p=T->firstchild;p;p=p->nextsibling)
if((d=depth(p))>max) max=d;
return max+1;
}
}
//
int num=0;
int number_leaf(CSTree T)
{
if(T)
{
if(!T->firstchild) num++;
number_leaf(T->firstchild);
number_leaf(T->nextsibling);
}
return num;
}
//
int main()
{
CSTree T;
int d;
CreateCSTree(T);
printf("PreOrder: ");
PreOrderTraverse(T);
printf("\n");
printf("PostOrder: ");
PostOrderTraverse(T);
printf("\n");
d=depth(T);
printf("Depth:");
printf("%d\n",d);
number_leaf(T);
printf("Number of leaves:");
printf("%d\n",num);
return 0;
}
```