试编写算法,对一棵以孩子-兄弟链表表示的树统计其叶子结点的个数,c语言
时间: 2024-06-13 18:09:52 浏览: 98
轻松搞定面试中的链表题目
以下是一棵以孩子-兄弟链表表示的树统计其叶子结点的个数的C语言算法:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_TREE_SIZE 100
typedef struct CSNode {
char data;
struct CSNode *firstchild, *nextsibling;
} CSNode, *CSTree;
int countLeaf(CSTree T) {
if (T == NULL) {
return 0;
} else if (T->firstchild == NULL) {
return 1 + countLeaf(T->nextsibling);
} else {
return countLeaf(T->firstchild) + countLeaf(T->nextsibling);
}
}
int main() {
// 构建一棵以孩子-兄弟链表表示的树
CSTree T = (CSTree) malloc(sizeof(CSNode));
T->data = 'A';
T->firstchild = (CSTree) malloc(sizeof(CSNode));
T->firstchild->data = 'B';
T->firstchild->firstchild = (CSTree) malloc(sizeof(CSNode));
T->firstchild->firstchild->data = 'D';
T->firstchild->firstchild->firstchild = NULL;
T->firstchild->firstchild->nextsibling = (CSTree) malloc(sizeof(CSNode));
T->firstchild->firstchild->nextsibling->data = 'E';
T->firstchild->firstchild->nextsibling->firstchild = NULL;
T->firstchild->firstchild->nextsibling->nextsibling = NULL;
T->firstchild->nextsibling = (CSTree) malloc(sizeof(CSNode));
T->firstchild->nextsibling->data = 'C';
T->firstchild->nextsibling->firstchild = (CSTree) malloc(sizeof(CSNode));
T->firstchild->nextsibling->firstchild->data = 'F';
T->firstchild->nextsibling->firstchild->firstchild = NULL;
T->firstchild->nextsibling->firstchild->nextsibling = (CSTree) malloc(sizeof(CSNode));
T->firstchild->nextsibling->firstchild->nextsibling->data = 'G';
T->firstchild->nextsibling->firstchild->nextsibling->firstchild = NULL;
T->firstchild->nextsibling->firstchild->nextsibling->nextsibling = NULL;
T->firstchild->nextsibling->nextsibling = NULL;
// 统计叶子结点的个数
int leafCount = countLeaf(T);
printf("The number of leaf nodes is: %d\n", leafCount);
return 0;
}
```
阅读全文