Search code examples
binary-tree

Minimum Depth of Binary Tree - returns None


I am working on LeetCode problem 111. Minimum Depth of Binary Tree:

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

I have used a breadth first algorithm and tried to change it to align it to the problem. But the function is returning None.

Could anyone explain why that happens?

def minDepth(self, root: Optional[TreeNode]) -> int:
        queue=[]
        if root==None:
            return 0
        level=1
        while(len(queue)>0):
            n=len(queue)
            for i in range(n):
                node=queue.pop(0)
                if not node.right and not node.left:
                    return(level)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            level+=1

Solution

  • The problem is that your queue is empty at the moment the loop is about to start.

    You should place the root node in it:

            if root is None:
                return 0
            queue = [root]  # <----
            level = 1
            while queue:  
                # ...etc