简体   繁体   中英

How to carry variable through recursive function in Python?

I was doing some leetcode problems and found that I couldn't carry my variables through recursive functions as I thought I could.

So for example, say I wanted to sum all of nodes of a tree.

So I thought of implementing it this way:

def Sum(root):


    def dfs(root,x):
        if root:
            dfs(root.left, x)
            x.append(root.val)
            dfs(root.right,x)

        return x

    return(sum(dfs(root,x=[])))

And this works. However, say I want to cut down on memory, how come this implementation doesn't work and just returns the root node.

def Sum(root):


    def dfs(root,x):
        if root:
            dfs(root.left, x)
            x+=(root.val)
            dfs(root.right,x)

        return x

    return(sum(dfs(root,x=0)))

Any help or guidance would be appreciated.

x is mutable in your first definition; each call to dfs gets a reference to the same list.

In your second example, x is immutable . The value of x is not modified by the recursive call; x += root.val just updates the local copy of the argument.

Instead, you need to add the return value of dfs directly to x .

def Sum(root):
    def dfs(root, x):
        if root:
            x += dfs(root.left, x)
            x += root.val
            x += dfs(root.right,x)
        return x

    return dfs(root, x=0)

There's no need to define dfs , since you aren't really doing a generic search or walk any more. Just call Sum recursively. Also, the return value is sufficient; you don't need an x argument at all.

def Sum(root):
    if not root:
        return 0
    else:
        return Sum(root.left) + root.val + Sum(root.right)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM