0

Can someone help me figure out what's wrong with my code?

This test case doesn't work - [2,null,3,null,4,null,5,null,6] - my code returns 0 instead of 5. Not sure why.

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if root.left is None and root.right is None:
            return 0
        elif root.left is None and root.right is not None:
            return self.minDepth(root.right)
        elif root.right is None and root.left is not None:
            return self.minDepth(root.left)
        else:
            return 1 + min(self.minDepth(root.left), self.minDepth(root.right))

Thank you!

2
  • 1
    Why are you not adding 1 to the recursive call in all of the cases? Commented May 8, 2021 at 17:42
  • This would be so easy to solve if you would just debug and step through the code, and look at the values that variables have an function calls return. Once you do that, you'll find no reason to post this question. Commented May 8, 2021 at 17:52

1 Answer 1

1

You should check the root it self first, in case the input is an empty tree (root is None). You will get an NPE without this null check. And you need to include the current root itself in the elif block as well. This is my accepted code:

class Solution(object):
    def minDepth(self, root):
        if root is None:
            return 0
        elif root.left is None and root.right is not None:
            return self.minDepth(root.right) + 1
        elif root.right is None and root.left is not None:
            return self.minDepth(root.left) + 1
        else:
            return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
Sign up to request clarification or add additional context in comments.

2 Comments

Just changed the solution to a python version
Omg of course! thank you so much. Let me know if you have a better solution for the problem :)

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.