[LeetCode]104. Maximum Depth of Binary Tree

104. Maximum Depth of Binary Tree

class Solution(object):
    res = 1
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def helper(cur, path):
            if not cur:
                return
            self.res = max(self.res, path)
            if cur.left:
                helper(cur.left, path + 1)
            if cur.right:
                helper(cur.right, path + 1)
        if not root:
            return 0
        helper(root, 1)
        return self.res

可以写得更简单一些:

class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        return 0 if not root else max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
posted @ 2017-08-30 13:28  banananana  阅读(130)  评论(0编辑  收藏  举报