LeetCode C++ 111. Minimum Depth of Binary Tree【DFS/BFS】简单
发布日期:2021-07-01 02:49:57
浏览次数:2
分类:技术文章
本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
路过,博主的博客真漂亮。。
[***.116.15.85]2024年04月29日 00时53分30秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
[转帖]Robots.txt指南
2019-05-01
Eclipse + MyEclipse下配置J2EE工程(英文界面)
2019-05-01
Eclipse及其插件下载网址大全
2019-05-01
正则表达式简介(微软)--6.优先权顺序
2019-05-01
多用户与多租户的区别
2019-05-01
Python自动化运维 - day14 - JavaScript基础
2019-05-02
oracle保存小数点前为"0"的问题
2019-05-02
linux sar 命令详解
2019-05-02
ipvsadm 安装配置
2019-05-02
Linux shell脚本的字符串截取
2019-05-02
数据库复习(4)
2019-05-02
1小时点击量破千万!阿里巴巴首发:MySQL高级调优笔记!全是技术重点
2019-05-02
这个GItHub上的Java项目开源了 2021最全的Java架构面试复习指南
2019-05-02
Proftpd MySQL [Step by Step]
2019-05-02
EFI Shell 命令参考
2019-05-02
HP-UX oracle RAC 双机实践
2019-05-02
解决SHELL脚本中的export无法生效的问题【转】
2019-05-02