Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading