UPDATE: To keep the recursive approach and fix the existing code, simply change line 3,
ie. self._MinVal(node.left) to return self._MinVal(node.left).
The addition of the return keyword there
will ensure that the return value will bubble up from the bottom of
the recursion stack.
def _MinVal(self, node):
if node.left != None:
self._MinVal(node.left)
else:
res = node.data
print(res)
return res
When you print(res) you get the last traversed node to the left, which is your correct answer. However, when you return res, you are returning the value to the previous function call in the recursive stack. Which means that your correct answer is returned to the function call execution at the previous node, where you have no return value. You are not passing your found value back up the stack, which is why the topmost instance returns None.
Try this, and it should work:
#Pass root node to this function
def minValue(node):
current = node
# loop down to find the lefmost leaf
while(current.left is not None):
current = current.left
return current.data
This function should do what you need, fairly smoothly.
ifblock just changeself._MinVal(node.left)toreturn self._MinVal(node.left)