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);
} };

最新文章

  1. 如何将网页的title前面的图标替换成自己的图标
  2. Compare Version Numbers
  3. Android之AnimationDrawable初识
  4. Linux makefile 教程 非常详细,且易懂
  5. 开源免费的HTML5游戏引擎——青瓷引擎(QICI Engine) 1.0正式版发布了!
  6. WPF学习笔记——认识XAML
  7. hdu4737 A Bit Fun ——O(n)做法、错误的做法 + 正确做法
  8. Angularjs,WebAPI 搭建一个简易权限管理系统 —— 基本功能演示(二)
  9. ORACLE十进制与十六进制的转换
  10. Haar特征
  11. 关于ligerui 中 grid 表格的扩展搜索功能在远程数据加载时无法使用的解决办法
  12. 解决ORA-00904: invalid identifier标识符无效
  13. x86_64是什么意思
  14. 搭建一个MP-demo(mybatis_plus)
  15. java基础语法运算符
  16. Activity(活动)
  17. js实现字体闪烁
  18. 【搜索】POJ-3187 枚举全排列
  19. [self.view addSubview:vc2.view]程序崩溃的解决办法
  20. Linux PHP 编译参数详解(二)

热门文章

  1. 3.Jmeter 快速入门教程(三-1) --添加响应断言(即loadrunner中所指的检查点)
  2. shell getopts命令
  3. Scrapy框架: 第一个程序
  4. C語言中資料結構(struct)的大小
  5. Groovy学习:第三章 Groovy开发环境
  6. 1006 -- Biorhythms
  7. teb-安装
  8. egrep 正则
  9. Nodejs base64编码与解码
  10. Linux编译C语言程序