
Leedcode1-求树的最小高度
发布日期:2025-04-04 18:29:35
浏览次数:13
分类:精选文章
本文共 1969 字,大约阅读时间需要 6 分钟。
#include#include #include using namespace std; // 处理二叉树深度问题 // 情况分析:空树;没有子树;只有左/右子树;有两子树 struct BinaryNode { BinaryNode *left; BinaryNode *right; int data; }; struct BinaryTree { BinaryNode *head; }; // 后序遍历实现深度计算 int getDepth(BinaryNode *node) { if (node == NULL) { return 0; } int left_depth = getDepth(node->left); int right_depth = getDepth(node->right); if (left_depth && right_depth) { return min(left_depth, right_depth) + 1; } else { return max(left_depth, right_depth) + 1; } } // 层次遍历实现深度计算 int getDepth2(BinaryNode *root) { if (root == NULL) { return 0; } queue q; q.push(root); int depth = 0; while (!q.empty()) { queue qt; depth++; while (!q.empty()) { BinaryNode *temp = q.front(); q.pop(); if (!temp->left && !temp->right) { return depth; } if (temp->left) { qt.push(temp->left); } if (temp->right) { qt.push(temp->right); } } q = qt; } return depth; } int main() { // 构建示例二叉树 BinaryTree btree; BinaryNode node1 = { NULL, NULL, 7 }; BinaryNode node2 = { NULL, NULL, 9 }; BinaryNode node3 = { NULL, NULL, 8 }; BinaryNode node4 = { NULL, NULL, 4 }; BinaryNode node5 = { NULL, NULL, 2 }; BinaryNode node6 = { NULL, NULL, 5 }; BinaryNode node7 = { NULL, NULL, 10 }; btree.head = &node1; node1.left = &node3; node1.right = &node2; node2.right = &node7; node3.left = &node4; node4.left = &node5; node4.right = &node6; // 计算树的深度 int height = getDepth2(&node1); cout << height << endl; } 运行结果:
发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2025年04月30日 03时12分40秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
iOS_Runtime3_动态添加方法
2019-03-07
我用wxPython搭建GUI量化系统之最小架构的运行
2019-03-07
selenium+python之切换窗口
2019-03-07
map[]和map.at()取值之间的区别
2019-03-08
VTK:可视化之RandomProbe
2019-03-09
【编程】C语言入门:1到 100 的所有整数中出现多少个数字9
2019-03-09
pair的用法
2019-03-09
javaWeb服务详解(含源代码,测试通过,注释) ——Emp的Dao层
2019-03-11
echarts 基本图表开发小结
2019-03-11
TreeSet、TreeMap
2019-03-11
GitHub上传时,项目在已有文档时直接push出现错误解决方案
2019-03-11
嵌入式系统试题库(CSU)
2019-03-12
00010.02最基础客户信息管理软件(意义类的小项目,练习基础,不涉及数据库)
2019-03-12
00013.05 字符串比较
2019-03-12
UE4 错误列表 error码(只记录我遇到的情况,持续添加,未完成)
2019-03-13
Android 架构组件 – 让天下没有难做的 App
2019-03-13
能解决数据可视化大屏需求的3款可视化工具
2019-03-13
第01问:MySQL 一次 insert 刷几次盘?
2019-03-13