最大深度
class Solution:
def maxDepth(self, root: TreeNode) -> int:
# leetcode submit region end(Prohibit modification and deletion)
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
最小深度
注意:左子树、或者右子树为空就直接,加另一边的最小值
class Solution:
def minDepth(self, root: TreeNode) -> int:
# leetcode submit region end(Prohibit modification and deletion)
if not root:
return 0
if not root.left:
return 1+self.minDepth(root.right)
if not root.right:
return 1+self.minDepth(root.left)
return 1 + min(self.minDepth(root.left), self.minDepth(root.right))