[LeetCode] Minimum Depth of Binary Tree 二叉树最小深度
2024-08-31 06:00:21
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
这题是找二叉树的最小深度,这是广度搜索比较好吧,为啥提示给的是 深度优先呢。
- 判断树是否为空
- 将root 节点压入队列
- while 队列不为空
- 计算当前队列的个数,进行这么多次的第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 ;
}
最新文章
- 自定义一个叫 ReadOnlyXmlMembershipProvider 的 MembershipProvider,用 XML 作为用户储藏室
- https://github.com/akullpp/awesome-java
- [OSG][转]osg格式文件
- HttpModule和Http Handler (比较与区别)
- visual studio 中快捷键的使用
- SQL Server删除表信息的三种方法
- swift UILable的用法
- IOS tableViewCell单元格重用中的label重叠的问题
- Android学习笔记-EditText(输入框)(一)
- 关于CSS 的position定位问题
- Spring Integration实现分布式锁
- C与C++中实现 gotoxy()函数
- java.lang.NoSuchMethodError: javax.wsdl.xml.WSDLReader.readWSDL
- Thinkphp3.2+PHPQRCode 二维码生成示例
- 高通 添加 cmdline
- Oracle 默认的driectory 目录
- ACM International Collegiate Programming Contest World Finals 2013
- AXFR和IXFR区域传输及原理
- linq to datatable 和lambda查询datatable
- EF--Code First配置问题