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.