二叉树的最小深度
二叉树的最小深度
力扣刷题:111. 二叉树的最小深度
在做完二叉树的最大深度后,做二叉树的最小深度出错!
究其原因,是没有理解深度的定义和理解递归
首先,题目中对深度的定义为:
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。是叶子结点,及左右孩子都为空的结点。
错误代码如下:
if (node == NULL) return 0;
int leftDepth = getDepth(node->left);
int rightDepth = getDepth(node->right);
int result = 1 + min(leftDepth, rightDepth);
return result;
当左右结点有一个结点为空,另一个不为空时出错!
在求最大深度的过程中,会淘汰调结点为空的那边,
而在求最小深度的过程中,并不会淘汰而是保留,而这是不符合条件的情况
所以,需要考虑左右结点为空的情况
正确代码如下:
class Solution {
public:
//当左子树为空时,不构成子树,最小深度要求从根结点到叶子结点
int minDepth(TreeNode* root)
{
if (root == nullptr) {
return 0;
}
// 只有左节点为空
if (root->left ==nullptr && root->right !=nullptr) {
return 1 + minDepth(root->right);
}
// 只有右节点为空
if (root->right ==nullptr && root->left !=nullptr) {
return 1 + minDepth(root->left);
}
//左右结点都为空或都不为空
return 1 + min(minDepth(root->left), minDepth(root->right));
}
};