My solution in python


  • 18

    The idea is to use recursion, the accepted short python code looks like follows:

    class Solution:
        # @param root, a tree node
        # @return an integer    
        def minDepth(self, root):
            if root == None:
                return 0
            if root.left==None or root.right==None:
                return self.minDepth(root.left)+self.minDepth(root.right)+1
            return min(self.minDepth(root.right),self.minDepth(root.left))+1

  • 0
    S
    This post is deleted!

  • 0
    S
    This post is deleted!

  • 0
    Z

    The "return self.minDepth(root.left)+self.minDepth(root.right)+1" is so great!


  • 6
    C

    Nice idea, while the following code is also feasible:

    def minDepth(self, root):
        if not root:
            return 0
        if not root.left or not root.right:
            return max(self.minDepth(root.left), self.minDepth(root.right)) + 1
        else:
            return min(self.minDepth(root.left), self.minDepth(root.right)) + 1

  • 0
    S

    Great idea! Thank you!


  • 0
    S

    Nice rewrite! But maybe I a python newbie, I always think 'root == None' is more pythonic than 'not root'.


  • 2

    Same idea here:

    class Solution(object):
        def minDepth(self, root):
            if not root: 
                return 0;
            l = self.minDepth(root.left);
            r = self.minDepth(root.right);
            return l + r + 1 if l == 0 or r == 0 else min(l, r) + 1;

  • 0
    Q
    This post is deleted!

  • 0
    S

    @caikehe said in My solution in python:

    Nice idea, while the following code is also feasible:

    def minDepth(self, root):
        if not root:
            return 0
        if not root.left or not root.right:
            return max(self.minDepth(root.left), self.minDepth(root.right)) + 1
        else:
            return min(self.minDepth(root.left), self.minDepth(root.right)) + 1

  • 0
    J

    What situation will the root == None ?

    In the if root.left==None or root.right==None: this has hold it to be not none?


  • 0
    J

    @jzc I ask a really stupid question.......
    sorry....


  • 0
    C
    This post is deleted!

Log in to reply
 

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