Given a Binary Tree, I wanted to find the depth at which a specific value appears.
def find_depth_of_val(self, root, val):
if not root:
return 10000000
if root.val == val:
return 0
return 1 + min(self.find_node(root.right, val), self.find_node(root.left, val))
This is the idea I had, you'll probably see a wild "return 10000000", which I used to make it so that if there is nothing else on a specific path, i.e. a leaf's next has been reached without finding the node we want, that the function knows the answer isn't there and doesn't return that possibility.
What I'm wondering is whether there's a better way to do this, one without using a random "return 10000000".
Edit: Someone gave me a solution in which I kind of change it to:
def find_depth_of_val(self, root, val):
if not root:
return None
if root.val == val:
return 0
right_side = self.find_node(root.right, val)
left_side = self.find_node(root.left, val)
if right_side is None:
return left_side
elif left_side is None:
return right_side
else:
return 1 + min(self.find_node(root.right, val), self.find_node(root.left, val))
In such a case like this, how should I type hint it considering we could be returning either None or an integer? That said, I'm still open to seeing if anyone else has any different solution designs!!
float('inf')ormath.inf.