1

I am trying to solve a problem that requires finding the minimum depth of a binary tree. I can't seem to find the error. Any advice would be of great help.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        
        queue = []
        queue = collections.deque(queue)
        queue.append(root)
        depth = 0
        
        while len(queue) != 0:
            numberOfNodes = len(queue)
            
            while numberOfNodes > 0:
                currentNode = queue.popleft()
                
                if not currentNode and not currentNode:
                    depth += 1
                    return depth
                
                if currentNode.left:
                    queue.append(currentNode.left)
                
                if currentNode.right:
                    queue.append(currentNode.right)
                
                numberOfNodes -= 1
            
            depth += 1
        return depth    
3
  • Is if not currentNode and not currentNode: a typo? I think it should be if not currentNode.left and not currentNode.right: Commented Aug 4, 2020 at 5:16
  • 1
    What a mistake I've made. Forgot to add left and right. Thank you so much for saving my time. Commented Aug 4, 2020 at 5:23
  • Haha, no worries. It happens to everyone. Commented Aug 4, 2020 at 5:24

1 Answer 1

1

I think I found the slight error. In place of :

if not currentNode and not currentNode:
    depth += 1
    return depth

Maybe, it should be this:

if currentnode.left is None and currentnode.right is None:     
    return depth
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.