//树除了 递归 还有 循环 左右比较
class Solution {
public:
int minDepth(TreeNode* root) {
queue<TreeNode*> temq1;
queue<TreeNode*> temq2;
if(root == nullptr) return 0;
int count =1;
temq1.push(root);
TreeNode* temq = nullptr;
while(!temq1.empty())
{
while(!temq1.empty())
{
temq = temq1.front();
if(temq->left == nullptr && temq->right == nullptr) return count;
if(temq->left != nullptr) temq2.push(temq->left);
if(temq->right != nullptr) temq2.push(temq->right);
temq1.pop();
}
count++;
// 重新赋值temq1
while(!temq2.empty())
{
temq1.push(temq2.front());
temq2.pop();
}
}
return count;
}
};
// 递归 深度 nullptr 0 lert&& right == null 1 min,max(left,right) + n
#include <algorithm>
using namespace std;
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL)
return 0;
if(root->left == NULL && root->right == NULL)
return 1;
int leftDepth = INT_MAX;
int rightDepth = INT_MAX;
if(root->left != NULL)
leftDepth = minDepth(root->left);
if(root->right !=NULL)
rightDepth = minDepth(root->right);
return min(leftDepth,rightDepth) +1;
}
};
49 - 算法 - Leetcode-111 -二叉树的最小深度 -递归循环
最新推荐文章于 2024-05-30 21:00:00 发布
这篇博客介绍了两种计算二叉树最小深度的方法:一种是使用广度优先搜索(BFS)的循环实现,另一种是通过递归。在BFS方法中,利用队列进行层次遍历,当遇到叶子节点时返回当前层数。递归方法则是通过分别计算左子树和右子树的最小深度,取最小值加1作为整个树的最小深度。这两种方法都有效地解决了问题。
摘要由CSDN通过智能技术生成