力扣算法题—111.Minimum Depth of Binary Tree
2024-10-07 18:02:46
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.
Solution:
使用深度遍历和广度遍历
class Solution {
private:
int minLevel = INT32_MAX;
public:
int minDepth(TreeNode* root) {
if (root == nullptr)return ;
//return BFS(root);
int res = INT32_MAX;
DFS(root, , res);
return res;
} int BFS(TreeNode* root)
{
queue<TreeNode*>q;
q.push(root);
int level = ;
while (!q.empty())
{
queue<TreeNode*>temp;
++level;
while (!q.empty())
{
TreeNode* p = q.front();
q.pop();
if (p->left == nullptr && p->right == nullptr)return level;
if (p->left != nullptr)temp.push(p->left);
if (p->right != nullptr)temp.push(p->right);
}
q = temp;
}
return level;
}
void DFS(TreeNode* root, int level, int &res)
{
if (root->left == nullptr && root->right == nullptr) {
res = res > level ? level : res;
return;
}
if (root->left != nullptr)DFS(root->left, level + , res);
if (root->right != nullptr)DFS(root->right, level + , res);
} };
最新文章
- 如何将网页的title前面的图标替换成自己的图标
- Compare Version Numbers
- Android之AnimationDrawable初识
- Linux makefile 教程 非常详细,且易懂
- 开源免费的HTML5游戏引擎——青瓷引擎(QICI Engine) 1.0正式版发布了!
- WPF学习笔记——认识XAML
- hdu4737 A Bit Fun ——O(n)做法、错误的做法 + 正确做法
- Angularjs,WebAPI 搭建一个简易权限管理系统 —— 基本功能演示(二)
- ORACLE十进制与十六进制的转换
- Haar特征
- 关于ligerui 中 grid 表格的扩展搜索功能在远程数据加载时无法使用的解决办法
- 解决ORA-00904: invalid identifier标识符无效
- x86_64是什么意思
- 搭建一个MP-demo(mybatis_plus)
- java基础语法运算符
- Activity(活动)
- js实现字体闪烁
- 【搜索】POJ-3187 枚举全排列
- [self.view addSubview:vc2.view]程序崩溃的解决办法
- Linux PHP 编译参数详解(二)