How to return value from recursive function in python?

六月ゝ 毕业季﹏ 提交于 2019-12-24 08:30:19

问题


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 a value from this recursive function. I'm a total newbie in python.

def return_key(self, val, node):
    if(val < node.v):
        if(node.l != None):
            self.return_key(val, node.l)
        else:
            print node.v
            return node
    else:
        if(node.r != None):
            #print node.v
            self.return_key(val, node.r)
        else:
            print node.v
            return node

Printing node.v prints the node value, but when i print the returned node :

print ((tree.return_key(6, tree.getRoot().v)))

it prints

None

as result.


回答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 is not None:
    return self.return_key(val, node.l)

# ...

if node.r is not None:
    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:

def return_key(self, val):
    if val < self.v:
        if self.l is not None:
            return self.l.return_key(val)
    elif val > self.v:
        if self.r is not None:
            return self.r.return_key(val)

    # val == self.v or child node is None
    return 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.



来源:https://stackoverflow.com/questions/39159573/how-to-return-value-from-recursive-function-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!