[LeetCode] Minimum Depth of Binary Tree 二叉树最小深度

时间:2023-12-22 15:37:02

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