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