IV. Given a tree represented by left-child-right-sibling structure, please describe an algorithm that counts the number of leaf nodes on every level.(15 points)
给出一个用左孩子右邻居结构表示的树,请描述一个计算每层叶子节点个数的算法。
题目中用到的结构体定义:
typedef struct TreeNode *Tree;
struct TreeNode {
Tree Child;
int key;
Tree Sibling;
};
int Counter[MAX_LEVEL] ;
/* Counter[i] stores the number of leaves on the i-th level.*/
/* The root is on the level 0. */
void Count_Leaves( Tree T )
以下图为例 (其中A~M用数字1~13表示,验证结果)
此树等价于:
#include<bits/stdc++.h>
#define MAX_LEVEL 10
enum{child,sibling,null};
typedef struct TreeNode *Tree;
struct TreeNode{
Tree Child;
int key;
Tree Sibling;
};
Tree root;
int Counter[MAX_LEVEL];
void Count_Leaves(Tree T)
{
static int layer=0;
if(!T->Child){
Counter[layer]++;
}
else if(T->Child){
layer++;
Count_Leaves(T->Child);
layer--;
}
if(T->Sibling){
Count_Leaves(T->Sibling);
}
}
void Insert(Tree &T,int type,int x)
{
if(!T){
T=(Tree)malloc(sizeof(struct TreeNode));
T->key=x;
T->Sibling=NULL;
T->Child=NULL;
root=T;
}
else{
Tree p;
p=(Tree)malloc(sizeof(struct TreeNode));
p->key=x;
p->Child=NULL;
p->Sibling=NULL;
if(type==child)T->Child=p;
else if(type==sibling)T->Sibling=p;
}
}
int main()
{
int i;
memset(Counter,0,sizeof(Counter));
Tree T=NULL;
Insert(T,null,1);
Insert(T,child,2);
Insert(T->Child,sibling,3);
Insert(T->Child->Sibling,sibling,4);
Insert(T->Child->Sibling,child,7);
Insert(T->Child,child,5);
Insert(T->Child->Child,child,11);
Insert(T->Child->Child,sibling,6);
Insert(T->Child->Child->Child,sibling,12);
Insert(T->Child->Sibling->Sibling,child,8);
Insert(T->Child->Sibling->Sibling->Child,child,13);
Insert(T->Child->Sibling->Sibling->Child,sibling,9);
Insert(T->Child->Sibling->Sibling->Child->Sibling,sibling,10);
Count_Leaves(T);
for(i=0;i<MAX_LEVEL;i++){
printf("%d ",Counter[i]);
}
return 0;
}