//树除了 递归 还有 循环 左右比较
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 -二叉树的最小深度 -递归循环
最新推荐文章于 2022-06-07 11:13:09 发布