树采用孩兄弟链表作为存储结构,设计非递归算法求树的叶子结点数

树采用孩兄弟链表作为存储结构,设计非递归算法求树的叶子结点数

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值