0

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.

1

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

That makes sense to me. Thank you for explaining it so clearly.

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.