求二叉树的深度和宽度
来源:互联网 发布:ubuntu如何打开软件 编辑:程序博客网 时间:2024/06/05 06:38
题目标题:
求二叉树的宽度和深度
给定一个二叉树,获取该二叉树的宽度和深度。
例如输入
a
/ \
b c
/ \ / \
d e f g
返回3.
详细描述:
接口说明
原型:
int GetBiNodeInfo(BiNode &head, unsigned int *pulWidth, unsigned int *pulHeight)
输入参数:
head 需要获取深度的二叉树头结点
输出参数(指针指向的内存区域保证有效):
pulWidth 宽度
pulHeight 高度
返回值:
0 成功
1 失败或其他异常
代码如下:
#include <iostream>#include <queue>#include <algorithm>using namespace std;typedef struct tagBiNode //定义二叉树结构{char data;struct tagBiNode *left;struct tagBiNode *right;} BiNode;int getWidth(BiNode* head) //求宽度{if (head == NULL)return 0;queue<BiNode*> q;//定义一个队列q.push(head);//根结点入队int width = 1, current = 1;//初始化上一层和当前层的宽度while (!q.empty()) {while (current--) {if (q.front()->left != NULL)//队列头结点不为空,则入队q.push(q.front()->left);if (q.front()->right != NULL)q.push(q.front()->right);q.pop();//队列头元素出队}current = q.size();//当前层的宽度,即队列的长度width = max(width, current);//取上一层和当前层宽度的最大值}return width;}int getHeight(BiNode* head) //递归求深度{if (head == NULL)return 0;return max(getHeight(head->left), getHeight(head->right)) + 1;//左右子树深度的最大值加1}int GetBiNodeInfo(BiNode &head, unsigned int *pulWidth,unsigned int *pulHeight) {*pulWidth = getWidth(&head);*pulHeight = getHeight(&head);return 0;}参考资料:这里
0 0
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉数的深度和宽度
- 求二叉数的深度和宽度
- 求二叉树宽度和深度
- 华为练习 求二叉树的宽度和深度
- 求二叉树的深度和宽度[Java]
- 求二叉树的深度和宽度平衡最大距离
- 求二叉树的深度、宽度和叶子结点数
- 华为oj 求二叉树的深度和宽度
- 求二叉树的深度和宽度[Java]
- 求二叉树的深度和宽度[Java]
- awk printf 函数
- 李白打酒
- MFC CAsynocSocket的用法
- Android一些属性常识
- android 百度地图3.0
- 求二叉树的深度和宽度
- Git使用心得
- POJ 2955 - Brackets(区间DP)
- 源代码统计程序
- Search for a Range 寻找一个区间 二分查找左边展开
- Oracle Database(1)-归档模式设置
- Number of 1 Bits
- python操作符的优先级 一图见分晓
- MySQL中找出数据库中以同一字符串开头的表名的所有表