当前位置: 首页 > news >正文

17121 求二叉树各种节点数

### 思路
1. 使用先序遍历的方式构造二叉树。
2. 使用递归函数 `CreateBiTree` 来构造二叉树。
3. 使用递归函数 `CountNodes` 来统计度为2、度为1和度为0的节点数。

### 伪代码
1. 定义二叉树节点结构 `BiTNode` 和二叉树指针 `BiTree`。
2. 定义 `CreateBiTree` 函数:
   - 读取一个字符。
   - 如果字符为 `#`,则当前节点为空。
   - 否则,创建一个新节点,并递归构造其左子树和右子树。
3. 定义 `CountNodes` 函数:
   - 如果当前节点为空,返回。
   - 如果当前节点有两个孩子,度为2的节点数加1。
   - 如果当前节点有一个孩子,度为1的节点数加1。
   - 如果当前节点没有孩子,度为0的节点数加1。
   - 递归统计左子树和右子树的节点数。
4. 在 `main` 函数中:
   - 调用 `CreateBiTree` 构造二叉树。
   - 调用 `CountNodes` 统计节点数。
   - 输出度为2、度为1和度为0的节点数。

### C++代码
 

#include "stdio.h"
#include "malloc.h"
#define TRUE 1
#define FALSE 0
#define OK  1
#define ERROR  0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int  Status;typedef char  ElemType;
typedef struct BiTNode{ElemType data;struct BiTNode *lchild,*rchild; // 左右孩子指针
} BiTNode, *BiTree;Status CreateBiTree(BiTree &T) {char ch;scanf("%c", &ch);if (ch == '#') {T = NULL;} else {if (!(T = (BiTNode *)malloc(sizeof(BiTNode)))) return ERROR;T->data = ch; // 生成根结点CreateBiTree(T->lchild); // 构造左子树CreateBiTree(T->rchild); // 构造右子树}return OK;
}void CountNodes(BiTree T, int &degree2, int &degree1, int &degree0) {if (T == NULL) return;if (T->lchild != NULL && T->rchild != NULL) {degree2++;} else if (T->lchild != NULL || T->rchild != NULL) {degree1++;} else {degree0++;}CountNodes(T->lchild, degree2, degree1, degree0);CountNodes(T->rchild, degree2, degree1, degree0);
}int main() {BiTree T;int degree2 = 0, degree1 = 0, degree0 = 0;CreateBiTree(T);CountNodes(T, degree2, degree1, degree0);printf("%d\n", degree2);printf("%d\n", degree1);printf("%d\n", degree0);return 0;
}


http://www.mrgr.cn/news/36460.html

相关文章:

  • 关于前端框架的对比和选择
  • 传统PC危险了,以后我只用云电脑了
  • 0基础学习HTML(二十一)总结
  • golang如何把微信支付结构体拼接为对参数按照key=value的格式,并按照参数名ASCII字典序排序
  • 1.5 测试用例
  • 国产OpenEuler与Centos全面之比较
  • Java | Leetcode Java题解之第436题寻找右区间
  • VB 实例:掌握 Visual Basic 编程的精髓
  • 高级java每日一道面试题-2024年9月26日-运维篇[分布式篇]-如何保证每个服务器的时间都是同步的?
  • 一组.NET MAUI绘制的开源控件 - AlohaKit
  • 读构建可扩展分布式系统:方法与实践15可扩展系统的基本要素
  • 2024必备中英互译利器全知道
  • 新版双向链表,添加了at, front, back, insert, emplace等为了兼容std.
  • Stable Diffusion绘画 | 插件-Addition Networks:单独控制LoRA
  • 【C++】继承(下)
  • Java | Leetcode Java题解之第437题路径总和III
  • Android中的异步任务处理与UI更新技巧
  • <<编码>> 第 17 章 自动操作(4)--其余电路
  • Redis实战--Redis集群的搭建与使用
  • QT实现图片隐写术