题目在这:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
思路分析:

看着这张二叉树的图,写递归,明确几个出口。
1.如果当前指针的左子树,右子树都是空的时候。返回0
2.如果当前指针的左子树不为空,返回左子树继续递归。
3.如果当前指针的右子树不为空,返回右子树继续递归。
4.如果当前左子树和右子树都不为空,返回左右子树中小的哪一个继续递归。
返回的时候别忘了加一
完整代码:
class Solution:
def minDepth(self, root: TreeNode) -> int:
def minDepth(root: TreeNode) -> int:
if not root : return 0
leftDepth = minDepth(root.left)
rightDepth = minDepth(root.right)
if leftDepth and rightDepth:
return 1+ min(leftDepth, rightDepth)
elif leftDepth :
return 1 + leftDepth
elif rightDepth:
return 1 +rightDepth
else:
return 1
return minDepth(root)

本文详细介绍了求解二叉树最小深度的递归算法实现。通过四个关键步骤,明确了算法的递归终止条件及返回值计算逻辑,为读者提供了清晰易懂的代码示例。

3万+

被折叠的 条评论
为什么被折叠?



