Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – how do I return value from recurrsion

I am trying to run this code for search an element in a binary tree. It works well but I cannot return the value but can display it.

Here is my code:

def getNodeAddress(self, data):
        print(self._getNodeAddress(data, self.root))
    
def _getNodeAddress(self, data, root):
        if root:
            if root.data == data:
                print("<<<< ", root.data)
                return root
            self._getNodeAddress(data, root.left)
            self._getNodeAddress(data, root.right)

def _getNodeAddress(self, data, root, res):
        if root:
            if root.data == data:
                print("<<<< ", root.data)
                res = root
            self._getNodeAddress(data, root.left, res)
            self._getNodeAddress(data, root.right, res)
        print(res)
        return res

So in the above method, it traverses the tree to look for the value as the variable key, when it finds one it prints as in the line "print("<<<< ", root.data)", which does display as expected. But now the issue arises when I need to return the value to the parent method which is "getNodeAddress". I cannot print the value in the parent method. It just print "None"
So my question is how do I return the value from a recursion.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I also tried the second approach as in the above code of the same method name, but still exactly the same the issue
Any help would really be appreciated

>Solution :

It looks like only the base case is actually returning anything. You need to add return statements in the non-base cases as well. For example:

def _getNodeAddress(self, data, root):
        if root:
            if root.data == data:
                print("<<<< ", root.data)
                return root
            res = self._getNodeAddress(data, root.left)
            if res is None:
                res = self._getNodeAddress(data, root.right)
            return res
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading