Skip to content Skip to sidebar Skip to footer

How To Return Value From Recursive Function In Python?

I'm working with binary tree in python. I need to create a method which searches the tree and return the best node where a new value can be inserted. But i'm have trouble returning

Solution 1:

You need to return the result of your recursive call. You are ignoring it here:

if(node.l != None):
    self.return_key(val, node.l)

and

if(node.r != None):
    self.return_key(val, node.r)

Recursive calls are no different from other function calls, you still need to handle the return value if there is one. Use a return statement:

if(node.l != None):
    return self.return_key(val, node.l)

# ...if(node.r != None):
    return self.return_key(val, node.r)

Note that since None is a singleton value, you can and should use is not None here to test for the absence:

if node.l isnotNone:
    return self.return_key(val, node.l)

# ...if node.r isnotNone:
    return self.return_key(val, node.r)

I suspect you are passing in the wrong arguments to the call to begin with however; if the second argument is to be a node, don't pass in the node value:

print(tree.return_key(6, tree.getRoot())) # drop the .v

Also, if all your node classes have the same method, you could recurse to that rather than using self.return_value(); on the Tree just do:

print tree.return_key(6)

where Tree.return_key() delegates to the root node:

def return_key(self, val):
    root = tree.getRoot()
    if root is not None:
        return tree.getRoot().return_key(val)

and Node.return_key() becomes:

defreturn_key(self, val):
    if val < self.v:
        if self.l isnotNone:
            return self.l.return_key(val)
    elif val > self.v:
        if self.r isnotNone:
            return self.r.return_key(val)

    # val == self.v or child node is Nonereturn self

I updated the val testing logic here too; if val < self.v (or val < node.v in your code) is false, don't assume that val > self.v is true; val could be equal instead.

Post a Comment for "How To Return Value From Recursive Function In Python?"