题目链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
难度:简单

描述:
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。

题解

与104.二叉树的最大深度类似,不过得判断是否为叶节点。

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def minDepth(self, root: TreeNode) -> int:
  9. if root is None:
  10. return 0
  11. left_height = self.minDepth(root.left)
  12. right_height = self.minDepth(root.right)
  13. if left_height == 0 or right_height == 0:
  14. return left_height + right_height + 1
  15. else:
  16. return min(left_height, right_height) + 1