https://leetcode.com/problems/minimum-depth-of-binary-tree/
题目强调“The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.”题目强调必须找到叶子节点。递归的终止条件是当当前节点没有子节点或当前节点为空时,停止递归。当递归遇到节点一个左节点为空时,此时递归返回他的右节点深度;同理,遇到右节点为空时,递归他的左节点;当两个节点都存在时,返回两个节点深度更小的值。
class Solution:
def minDepth(self, root: TreeNode) -> int:
# 终止条件,结束递归
if root == None:
return 0
if root.left == None and root.right == None:
return 1
# 开始递归
if root.left == None:
return self.minDepth(root.right) + 1
elif root.right == None:
return self.minDepth(root.left) + 1
else:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1