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.

Hide Tags

Tree Depth-first Search

 

    这题是找二叉树的最小深度,这是广度搜索比较好吧,为啥提示给的是 深度优先呢。
  1. 判断树是否为空
  2. 将root 节点压入队列
  3. while 队列不为空
  4. 计算当前队列的个数,进行这么多次的第5步
  5. 获取queue 头,弹出一个,判断弹出的时候为叶子,是的返回,不是将支点加入队列
 #include <iostream>
#include <queue>
using namespace std;
/**
* Definition for binary tree
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
}; class Solution {
public:
int minDepth(TreeNode *root) {
if(root ==NULL) return ;
queue<TreeNode* > qu;
TreeNode * curNode;
qu.push(root);
int ret =;
while(!qu.empty()){
ret ++;
int n = qu.size();
while(n-->){
curNode =qu.front();
qu.pop();
if(curNode->left==NULL&&curNode->right==NULL) return ret;
if(curNode->left!=NULL) qu.push(curNode->left);
if(curNode->right!=NULL) qu.push(curNode->right);
}
}
return ret;
}
}; int main()
{ Solution sol;
return ;
}

最新文章

  1. 自定义一个叫 ReadOnlyXmlMembershipProvider 的 MembershipProvider,用 XML 作为用户储藏室
  2. https://github.com/akullpp/awesome-java
  3. [OSG][转]osg格式文件
  4. HttpModule和Http Handler (比较与区别)
  5. visual studio 中快捷键的使用
  6. SQL Server删除表信息的三种方法
  7. swift UILable的用法
  8. IOS tableViewCell单元格重用中的label重叠的问题
  9. Android学习笔记-EditText(输入框)(一)
  10. 关于CSS 的position定位问题
  11. Spring Integration实现分布式锁
  12. C与C++中实现 gotoxy()函数
  13. java.lang.NoSuchMethodError: javax.wsdl.xml.WSDLReader.readWSDL
  14. Thinkphp3.2+PHPQRCode 二维码生成示例
  15. 高通 添加 cmdline
  16. Oracle 默认的driectory 目录
  17. ACM International Collegiate Programming Contest World Finals 2013
  18. AXFR和IXFR区域传输及原理
  19. linq to datatable 和lambda查询datatable
  20. EF--Code First配置问题

热门文章

  1. 【Python学习之八】ORM
  2. Linux更改文件权限(二)
  3. vue购物车的实现
  4. url地址形式的传参格式拼接
  5. HTML插入文件链接(如音乐,照片)
  6. Android 线程那些事儿
  7. Gradle task
  8. app分享代码
  9. BugKu 2B+基于python的opencv的安装-------CTF 盲水印的套路
  10. Python-S9-Day116——Flask框架相关