1 line Ruby and Python


  • 33

    Just a bit shorter/different than previous solutions.

    Ruby:

    def max_depth(root)
      root ? 1 + [max_depth(root.left), max_depth(root.right)].max : 0
    end
    

    Python:

    def maxDepth(self, root):
        return 1 + max(map(self.maxDepth, (root.left, root.right))) if root else 0

  • 0
    R

    @StefanPochmann This concise solution makes it tad slow. Any comments?


  • 0

    @kaddu What do you mean? How slow?


  • 0
    R

    @StefanPochmann

        def maxDepth(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            if root==None:
                return 0
            leftChildHeight=self.maxDepth(root.left)
            rightChildHeight=self.maxDepth(root.right)
            return max(leftChildHeight, rightChildHeight)+1
    

    This one is like 20 ms faster. I don't understand the reason though.


  • 2

    @kaddu I don't see that being faster. How often did you submit each and what were the individual times?


  • 0
    R

    @StefanPochmann Submitted each once only. One was 55ms and the other was 78ms. How does the OJ really work with the timing? I have noticed its mischievous at times.


  • 3

    @kaddu Once is not nearly enough. Especially with Python, where the system/judge usually take much of the time and that varies quite a bit. I think Java might still be the only language where the judge time is excluded (because earlier the Java judge time was very high (like 400 ms) and varying a lot as well, so an effort was made to fix that). I suggest you play around with solutions in several languages a bit, submit them several times and observe the acceptance time ranges to get a feeling for this.


  • 0

    I wrote an even shorter python version just for fun :)
    It's 2 characters shorter than yours.

        def maxDepth(self, root):
            return root and 1 + max(map(self.maxDepth, (root.left, root.right))) or 0
    

  • 0

    @jedihy How did you count? I think it's only one character shorter. Plus not as clean. But I've done that in golfing before, sure :-)


  • 0

    @StefanPochmann Lol, actually 1 char shorter, my bad.


Log in to reply
 

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