Simple and easy recursive Python Solution


  • 0
    L

    I am a beginner of Programming and Python is my first language.
    Just happy to solve this challenge myself so I want to share this simple and easy solution and my joy.

    Thinking:
    I have to count each level of node and find the max depth so that I figure out this simple formula:
    f(n) = 1 + max(f(n.left),f(n.right))
    1 is root as a default.

    class Solution(object):
        def maxDepth(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            if not root:
                return 0
            Sum = 1
            if root.left == None and root.right == None:
                return Sum
            return Sum + max(self.maxDepth(root.left),self.maxDepth(root.right))
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.