LeetCode C++ 111. Minimum Depth of Binary Tree【DFS/BFS】简单
发布日期:2021-07-01 02:49:57
浏览次数:3
分类:技术文章
本文共 1479 字,大约阅读时间需要 4 分钟。
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree[3,9,20,null,null,15,7]
, 3 / \ 9 20 / \ 15 7
return its minimum depth = 2
.
题意:找到二叉树的最小深度——从根结点到最近叶子结点的最短路径上的结点数量。
思路1:对二叉树首先想到的就是DFS,考虑二叉树的五种形态:
- 空树时直接返回
0
; - 只有根结点时,根结点就是叶子结点,返回
1
; - 存在左结点或者右结点时,根结点不是叶子结点,需要返回
2
—— 也就是根结点+左结点/右结点的高度; - 左右结点都存在时,需要返回它们之中更小的高度
+1
(根结点)。
代码如下:
class Solution { public: int minDepth(TreeNode* root) { if (root == nullptr) return 0; int lsum = minDepth(root->left), rsum = minDepth(root->right); return (lsum && rsum) ? min(lsum, rsum) + 1 : 1 + lsum + rsum; //前者是左右子树都存在时,后者是左右子树存在其一或者都不存在的情况 }};
思路2:BFS也行。不断计算层数,遇到叶子结点时直接返回高度。
代码如下:
class Solution { public: int minDepth(TreeNode* root) { if (root == nullptr) return 0; int height = 0; queueq; q.push(root); while (!q.empty()) { int size = q.size(); ++height; for (int i = 0; i < size; ++i) { TreeNode *t = q.front(); q.pop(); if (t->left) q.push(t->left); if (t->right) q.push(t->right); if (!t->left && !t->right) return height; } } return height; }};
效率:
执行用时:16 ms, 在所有 C++ 提交中击败了53.28% 的用户内存消耗:17.3 MB, 在所有 C++ 提交中击败了77.61% 的用户
转载地址:https://memcpy0.blog.csdn.net/article/details/108138920 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
做的很好,不错不错
[***.243.131.199]2024年04月10日 14时59分39秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
synchronized底层实现及锁的升级、降级
2019-05-01
PermGen space-永久区内存溢出
2019-05-01
Maven继承和聚合
2019-05-01
Apache Kafka:优化部署的 10 种最佳实践
2019-05-01
Leetcode 35. 搜索插入位置 c#
2019-05-01
[9] JMeter-常用函数的使用
2019-05-01
[12] JMeter-结果分析之图形图表
2019-05-01
使用aspose.words 18.6实现pdf文档转换
2019-05-01
Java数组详解
2019-05-01
vs中动态DLL与静态LIB工程中加入版本信息的方法
2019-05-01
大数据分析技术与应用一站式学习(值得收藏)_v20200418
2019-05-01
Qt 在windows下的串口读写
2019-05-01
自定义Starter
2019-05-01
分布式事务原理探究(一)
2019-05-01
spring cloud consul 应用的多实例名的解决
2019-05-01
人工智能为什么这么火?看看安防江湖30年血战就知道了
2019-05-01
“前端智能为安防产生新的数据价值”
2019-05-01
(8)CMake入门笔记--CMake语法
2019-05-01
头文件中 #ifndef---#define---#endif的作用
2019-05-01
Ant内置任务之whichresource
2019-05-01