0

I am trying to work on Binary tree in python and trying to get Min value in BST. But I am facing a small problem.

def MinVal(self):
    if self.root == None:
       return None
    else:
       return self._MinVal(self.root)

def _MinVal(self, node):
    if node.left != None:
       self._MinVal(node.left)
    else:
       res = node.data
       print(res)
       return res

When I print the res variable I am getting my answer but in the next statement when I return it, the value is shown None. Why is it so ?

2
  • how your node define? Commented Jun 28, 2017 at 6:16
  • in your if block just change self._MinVal(node.left) to return self._MinVal(node.left) Commented Jun 28, 2017 at 6:21

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I already use the while statement to get min value, I want to get my hands over recursion so was practicing that. Can you tell me the sol with recursion?
Sure thing! On line 3 of your code, replace self._MinVal(node.left) with return self._MinVal(node.left). The addition of return there will bubble up the value you return from the bottom of the recursion stack, right to the top.

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.