给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
题干很简单,跟上一节的区别不大,上一节找的是最大深度,这一节找的是最小深度。怎么判断是不是最小深度呢?一个父节点下两个子节点,如果左节点下没有树了,而右节点下还有继续的树,那左节点树的深度肯定比右节点小,根据这个思路可以编写代码。
完整代码如下:
class Solution:
def getDepth(self, node):
if node is None:
return 0
leftDepth = self.getDepth(node.left) # 左
rightDepth = self.getDepth(node.right) # 右
# 当一个左子树为空,右不为空,这时并不是最低点
if node.left is None and node.right is not None:
return 1 + rightDepth
# 当一个右子树为空,左不为空,这时并不是最低点
if node.left is not None and node.right is None:
return 1 + leftDepth
result = 1 + min(leftDepth, rightDepth)
return result
def minDepth(self, root):
return self.getDepth(root)
首先,根节点不存在的话返回0,分成左右节点开始递归。当左子树为空,右子树不为空时,那么在右子树上开始递归,直到找到最小深度再加上根节点的1;右子树为空,左子树不为空时同样思路。如果都为空,但根节点左子树深度为3,右子树深度为4,那就求最小值min(leftDepth, rightDepth)再加上根节点的1。