class Solution: def maxDepth(self, root): if(root.left is None or root.right is None): return 0 if(root.left is None): return max(maxDepth(root.left) + 1, 0) if(root.right is None): return max(0, maxDepth(root.right) + 1) return max(maxDepth(root.left) + 1, maxDepth(root.right) + 1)
It is asking the depth of an empty tree, which has depth 0. As the tree is empty, it is calling the function using
Solution.maxDepth(None). The first conditional checks if root.left is None, but root is None, so it translates to None.left, which fails. Add a check
if(root is None): return 0 first and it should pass that problem.
As a side note, I think your first conditional needs to be an
and, not an
or, otherwise the others will never be called, and your second and third conditionals need correction, since they try to expand the None child instead of its sibling. Also, if the children are None, but the root is not, then it has a height of 1, not 0.