树采用孩兄弟链表作为存储结构,设计非递归算法求树的叶子结点数
#include <stdio.h>
#include <stdlib.h>
// 定义结构体 TreeNode,表示树中的一个结点
struct TreeNode {
int val; // 结点的值
struct TreeNode *first_child; // 指向第一个子结点
struct TreeNode *next_sibling; // 指向下一个兄弟结点
};
// 函数 countLeafNodes 用于求树的叶子结点数
int countLeafNodes(struct TreeNode *root) {
// 如果根结点为空,则直接返回 0
if (root == NULL) return 0;
int count = 0; // 叶子结点数初始化为 0
// 创建队列
struct TreeNode **q = (struct TreeNode**)malloc(100 * sizeof(struct TreeNode*));
int head = 0, tail = 0; // 队头指针和队尾指针
// 将根结点入队
q[tail++] = root;
// 当队列不为空时,循环执行以下操作
while (head < tail) {
// 取出队头结点
struct TreeNode *node = q[head++];
// 如果当前结点没有子结点,则叶子结点数加 1
if (node->first_child == NULL) {
count++;
} else {
// 将当前结点的所有子结点依次入队
struct TreeNode *child = node->first_child;
while (child != NULL) {
q[tail++] = child;
child = child->next_sibling;
}
}
}
// 释放内存
free(q);
// 返回叶子结点数
return count;
}
int main() {
// 初始化树
// ...
printf("%d\n", countLeafNodes(root));
return 0;
}