【每周例题】力扣 C++ 二叉树的最小深度
二叉树的最小深度
题目

题目分析
1.首先我们可以处理最小深度为0与最小深度为1的情况:
最小深度为0:头结点为空;root == nullptr
最小深度为1:root->left == nullptr && root->right == nullptr
2.接下来分为左右子树处理,我们可以用递归来计算最小深度
3.最后比较左右子树的最小深度
4.minDepth函数通常用于计算二叉树的最小深度。最小深度是指从根节点到最近叶子节点的最短路径上的节点数量。叶子节点是那些没有子节点的节点。
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution
{
public:
int minDepth(TreeNode* root)
{
if (root == nullptr)
{
return 0;
}
if (root->left == nullptr && root->right == nullptr)
{
return 1;
}
int leftDepth = INT_MAX;
int rightDepth = INT_MAX;
if (root->left)
{
leftDepth = minDepth(root->left);
}
if (root->right)
{
rightDepth = minDepth(root->right);
}
return min(leftDepth, rightDepth) + 1;
}
};

浙公网安备 33010602011771号