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

6-8 最宽层次结点数 分数 10

文章目录

  • 1.题目描述
  • 2.本题ac答案
    • 2.1法一: 代码复用
    • 2.2法二: 顺序队列实现层序遍历
  • 3.C++层序遍历求最大宽度
    • 3.1层序遍历代码
    • 3.2求最大宽度

1.题目描述

在这里插入图片描述

2.本题ac答案

2.1法一: 代码复用

在这里插入图片描述

//二叉树第i层结点个数
int LevelNodeCount(BiTree T, int i)
{if (T == NULL || i < 1)return 0;if (i == 1) return 1;return LevelNodeCount(T->lchild, i - 1) + LevelNodeCount(T->rchild, i - 1);
}
int GetDepthOfBiTree(BiTree T)
{if (T == NULL)return 0;return GetDepthOfBiTree(T->lchild) > GetDepthOfBiTree(T->rchild) ? GetDepthOfBiTree(T->lchild) + 1: GetDepthOfBiTree(T->rchild) + 1;
}
int MaxWidth(BiTree T)
{int per = 0;int max = 0;for (int i = 1; i <= GetDepthOfBiTree(T); i++){per = LevelNodeCount(T, i);if (per > max)max = per;}return max;
}

2.2法二: 顺序队列实现层序遍历

int MaxWidth(BiTree T) 
{if (T == NULL)return 0;BiTree queue[100] = { 0 };BiTree cur = NULL;int begin = 0, end = 0;int perLevel = 0, max = 0;//每入队一个结点 end++表示有效数据加一queue[end++] = T;//begin != end: 队中还有结点 还未取到上一层所有结点的子结点while (begin != end){perLevel = end - begin;if (perLevel > max)max = perLevel;//cur指向队头结点 (马上就要被遗弃 因为已经被访问)//begin++表示当前结点已被遍历 当前结点被遗弃cur = queue[begin++];if (cur->lchild)queue[end++] = cur->lchild; if (cur->rchild)queue[end++] = cur->rchild;}return max;
}

3.C++层序遍历求最大宽度

3.1层序遍历代码

void LevelTraverse(BiTNode* T)
{if (T == nullptr)return;queue<struct BiTNode*> q;q.push(T);while (!q.empty()){BiTNode* front = q.front();cout << front->data;q.pop();if (front->lchild)q.push(front->lchild);if (front->rchild)q.push(front->rchild);}cout << endl;
}

3.2求最大宽度

typedef char ElemType;
typedef struct BiTNode
{ElemType data;struct BiTNode* lchild, * rchild;
}BiTNode, * BiTree;
int MaxWidth(BiTree T)
{if (T == nullptr)return 0;queue<BiTree> q;q.push(T);int max = 0;while (!q.empty()){//当前层结点数int perLevel = q.size();  if (perLevel > max)max = perLevel;//for循环的作用://遍历当前栈中的结点 拿出一个结点node 把它的孩子入栈后就删除node//此时栈中存的结点是下一层结点for (int i = 0; i < perLevel; i++){BiTree front = q.front();q.pop();if (front->lchild) q.push(front->lchild);if (front->rchild)q.push(front->rchild);}}return max;
}
http://www.lryc.cn/news/217553.html

相关文章:

  • Linux学习第28天:Platform设备驱动开发(二): 专注与分散
  • postgresql数组重叠(有共同元素)查询
  • ubuntu系统 生成RSA密钥对
  • 【RtpSeqNumOnlyRefFinder】webrtc m98: ManageFrameInternal 的帧决策过程分析
  • centos系统源码编译安装nginx,并编写服务脚本
  • 2023下半年软考高项答题技巧!
  • windows server 2016调优
  • Qt 插件开发详解
  • vue需求:实现签章/签字在页面上自由定位的功能(本质:元素在页面上的拖拽)
  • 【深度学习基础】Pytorch框架CV开发(1)基础铺垫
  • uniapp原生插件之安卓热敏打印机打印插件
  • 巴菲特:卖比亚迪有助于资金配置
  • 香港服务器有哪些特点
  • Leetcode76最小覆盖子串
  • GD32 单片机 硬件I2C死锁解决方法
  • SPSS两相关样本检验
  • 【vscode远程开发】使用内网穿透实现在公网环境下远程访问
  • KaiwuDB 内核解析 - SQL 查询的生命周期
  • 2023.11.03 homework
  • ssm在线互助答疑系统-计算机毕设 附源码 20862
  • MySQL中如何书写update避免锁表
  • Mysql库操作
  • C#中LINQtoSQL只能在.NetFramework下使用,不能在.net 下使用
  • Nacos 的底层实现原理 注册中心的两种调用方式
  • 视频编码格式和文件格式(多媒体容器格式)的关系
  • RHCSA --- 第二天
  • 作为一个初学者,入门大模型其实没那么难
  • 【QT】基本的绘图操作和高级绘图
  • layer.open再次渲染html,子页面调用在父页面打开弹出层,渲染html
  • 【Apache Flink】Flink DataStream API的基本使用