My two python solutions with recursion and iterative LIFO


  • 0
    M

    solution1 -- recursion
    class Solution(object):

    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root: return 0
        if not root.left and not root.right: return 1
        return min(self.minDepth(root.left)+1 if root.left else float('inf'),self.minDepth(root.right)+1 if root.right else float('inf'))
    

    And solution2 -- iterative LIFO
    class Solution(object):

    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        stack=[(root,1)]; ans=float('inf')
        while stack and root:
            node,dep=stack.pop()
            if not node.left and not node.right: ans=min(dep,ans)
            if node.left: stack+=(node.left,dep+1),
            if node.right: stack+=(node.right,dep+1),
        return ans if root else 0

Log in to reply
 

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