这段代码的问题在于 minDepth
函数中的返回值计算有误。当根节点为空时,应该返回 0 而不是 1。
以下是修正后的代码:
func Min(a, b int) int {
if a < b {
return a
}
return b
}
func Recursion(node *TreeNode) int {
if node == nil {
return 0
}
leftDepth := Recursion(node.Left)
rightDepth := Recursion(node.Right)
// 如果左子树或右子树为空,则取非空子树的深度 + 1
if node.Left == nil || node.Right == nil {
return leftDepth + rightDepth + 1
}
// 否则,取左右子树深度的较小值 + 1
return Min(leftDepth, rightDepth) + 1
}
func minDepth(root *TreeNode) int {
if root == nil {
return 0
}
return Recursion(root)
}
这样就可以正确计算二叉树的最小深度了。注意在判断左右子树为空时需要单独处理。
内容由零声教学AI助手提供,问题来源于学员提问