直接将maxDepth函数拿来使用时,实际上会考虑到空结点,若一个节点的一个子节点为空,另一个不为空,递归会提前返回,因此需要对子节点是否为空进行判断。
int minDepth(TreeNode *root)
{
if (root == nullptr)
{
return 0;
}
int left_path_depth = 1 + minDepth(root->left);
int right_path_depth = 1 + minDepth(root->right);
if (root->left == nullptr)
{
return right_path_depth;
}
if (root->right == nullptr)
{
return left_path_depth;
}
return left_path_depth <= right_path_depth ? left_path_depth : right_path_depth;
}