题目描述:
第一次提交:
class Solution(object):def minDepth(self, root):""":type root: TreeNode:rtype: int"""if not root:return 0if root.left and root.right:return min(self.minDepth(root.left)+1,self.minDepth(root.right)+1)if not root.left and root.right:return self.minDepth(root.right)+1if not root.right and root.left:return self.minDepth(root.left)+1if not root.left and not root.right:return 1
优化后:
class Solution(object):def minDepth(self, root):""":type root: TreeNode:rtype: int"""if not root: return 0if not root.left or not root.right:return 1 + max(self.minDepth(root.right), self.minDepth(root.left))else:return 1 + min(self.minDepth(root.right), self.minDepth(root.left))