This one is interesting. It tricked me, I had answered the wrong question at first! It is curious how it defines the depth, that it requires a leaf node. I was computing something else, something like max height.
This one’s interesting because it provides a somewhat (unless if I’m missing something) complicated inductive case. Good to know!
class Solution(object):
def minDepth(self, root):
if root is None:
return 0
lDepth = self.minDepth(root.left)
rDepth = self.minDepth(root.right)
# Were we a leaf?
if lDepth is 0 and rDepth is 0:
return 1
if lDepth is 0:
return rDepth + 1
if rDepth is 0:
return lDepth + 1
return min(lDepth, rDepth) + 1