鱼C论坛

 找回密码
 立即注册
查看: 347|回复: 1

[已解决]数据结构树的操作

[复制链接]
发表于 2023-11-13 18:40:20 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
请问,求一颗树中(不一定是二叉树)度为二的结点个数,怎么用C语言实现?
最佳答案
2023-11-13 18:40:33
你可以使用递归来实现。首先,定义一个函数来遍历树的每个节点并计算度为二的节点个数。在函数中,对于每个节点,你需要检查它的子节点个数(也就是它的度),如果度为二,则计数器加一。然后递归地对每个子节点调用这个函数。最后返回计数器的值即可。

以下是一个简单的C语言实现示例:

  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. struct TreeNode {
  4.     int data;
  5.     struct TreeNode* children[10]; // 假设每个节点最多有10个子节点
  6.     int numChildren;
  7. };

  8. int countDegreeTwoNodes(struct TreeNode* root) {
  9.     if (root == NULL) {
  10.         return 0;
  11.     }
  12.    
  13.     int count = 0;
  14.     if (root->numChildren == 2) {
  15.         count = 1;
  16.     }
  17.    
  18.     for (int i = 0; i < root->numChildren; i++) {
  19.         count += countDegreeTwoNodes(root->children[ i]);
  20.     }
  21.    
  22.     return count;
  23. }

  24. int main() {
  25.     // 在这里构建你的树,并调用 countDegreeTwoNodes 函数
  26.     return 0;
  27. }
复制代码


在这个示例中,我们假设每个节点最多有10个子节点,并定义了一个结构体  TreeNode  来表示树的节点。 countDegreeTwoNodes  函数用于计算度为二的节点个数。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-11-13 18:40:33 | 显示全部楼层    本楼为最佳答案   
你可以使用递归来实现。首先,定义一个函数来遍历树的每个节点并计算度为二的节点个数。在函数中,对于每个节点,你需要检查它的子节点个数(也就是它的度),如果度为二,则计数器加一。然后递归地对每个子节点调用这个函数。最后返回计数器的值即可。

以下是一个简单的C语言实现示例:

  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. struct TreeNode {
  4.     int data;
  5.     struct TreeNode* children[10]; // 假设每个节点最多有10个子节点
  6.     int numChildren;
  7. };

  8. int countDegreeTwoNodes(struct TreeNode* root) {
  9.     if (root == NULL) {
  10.         return 0;
  11.     }
  12.    
  13.     int count = 0;
  14.     if (root->numChildren == 2) {
  15.         count = 1;
  16.     }
  17.    
  18.     for (int i = 0; i < root->numChildren; i++) {
  19.         count += countDegreeTwoNodes(root->children[ i]);
  20.     }
  21.    
  22.     return count;
  23. }

  24. int main() {
  25.     // 在这里构建你的树,并调用 countDegreeTwoNodes 函数
  26.     return 0;
  27. }
复制代码


在这个示例中,我们假设每个节点最多有10个子节点,并定义了一个结构体  TreeNode  来表示树的节点。 countDegreeTwoNodes  函数用于计算度为二的节点个数。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-28 21:29

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表