recursion - what's difference between these two statements about passing variables in Python recursively -
i'm new python learner. , there question confusing me lot cause waste time think about.
there algorithm puzzle binary tree, , sum, should find root-to-leaf paths each path's sum equals given sum.
for example: given below binary tree , sum = 22
i have written python recursive method blew , runs correctly on online judgment.
#definition binary tree node. class treenode(object): def __init__(self, x): self.val=x self.left=none self.right=none class solution(object): def pathsum(self, root, sum): """ :type root: treenode :type sum: int :rtype: list[list[int]] """ res=[] if not root: return res temp=[root.val] self.helper(root,sum,res,temp) return res def helper(self, root, sum, res, temp): if not root: return 0 if root.left==none , root.right==none , sum==root.val: res.append(temp) if root.left!=none: self.helper(root.left,sum-root.val,res,temp+[root.left.val]) if root.right!=none: self.helper(root.right,sum-root.val,res,temp+[root.right.val]) in last 4 lines, invoke helper function recursively find path sum pass root left child , root right child.
however, if rewrite code below, mean last 4 lines
if root.left!=none: temp+=[root.left.val] self.helper(root.left,sum-root.val,res,temp) if root.right!=none: temp+=[root.right.val] self.helper(root.right,sum-root.val,res,temp) it gives me wrong answer , can't pass online judgment.
dose know difference between 2 kind of ways in pass parameter function in python. or it's declare , pass problem in code.
in view, can't see difference. everyone.help me !
+= alters list in-place:
>>> def inplace(l): ... l += ['spam'] ... >>> def new_list(l): ... l = l + ['spam'] ... >>> = ['foo'] >>> inplace(a) >>> ['foo', 'spam'] >>> = ['foo'] >>> new_list(a) >>> ['foo'] your original code passes in new list each time:
self.helper(root.left,sum-root.val,res,temp+[root.left.val]) but altered code shares temp across recursive calls , extends each time. matters because creating new list gave recursive calls left branch new, independent list right branch of recursion. extending list += give larger list right branch after processing left branch.
Comments
Post a Comment