A simple Python recursive solution - O(n) 60ms


  • 21
    G
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        # @param {TreeNode} root
        # @return {integer}
        def maxDepth(self, root):
            if not root:
                return 0
    
            return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

  • 0
    N

    @Google
    I am new to programming. I can't understand why self should be in the code. What does self mean? What's the meaning of self.maxDepth()? Thanks a lot.


  • 0
    G

    Hi, I'd suggest you go through a basic python tutorial before trying to tackle the problems. Personally I found this to be a very good one for beginner https://www.codecademy.com/learn/python

    Here self refer to the class itself, the maxDepth is a function definition, self.maxDepth() is a function call to the maxDepth function we defined in our class.

    What we are doing here is we are recursively calling the defined function until we reach to the leaf node.


  • 0
    G

    @nmbmlyx0211 ooops, forgot to mention you, please see my response


  • 0
    N

    @Google
    Hi,
    Thank you very much for your explanation. I'm learning Algorithm in Python. Recently I'm starting learning binary tree. I know the function definition, but I have no idea about class. This is the thing I need to learn. I don't know when I should use class. In my previous coding for list and array, I never see this kind of format like "self.function". That's why I think it should be like this without self.
    def maxDepth(root):
    if not root:
    return 0

        return 1 + max(maxDepth(root.left), maxDepth(root.right))
    

    Right now I know it doesn't work. I have to figure out what's the problem.
    Thanks again for your help.


Log in to reply
 

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