I am trying to solve a binary tree problem Path to Given Node using Python. I am confused about how the append function does reflect on a list I passed in the recursive function, but if I try to copy a list by value it does not work.
Append function
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param A : root node of tree
# @param B : integer
# @return a list of integers
def solve(self, A, B):
ans = []
self.f(A, B, [], ans)
return ans[0]
def f(self, node, val, cur, ans):
if(node == None): return
cur.append(node.val)
if(node.val == val):
ans.append(cur[:]) # Append. Does work!!!
return
self.f(node.left, val, cur, ans)
self.f(node.right, val, cur, ans)
cur.pop()
# Sample tree
root = TreeNode(3)
root.left = TreeNode(1)
root.right = TreeNode(4)
root.left.left = TreeNode(0)
root.left.right = TreeNode(-2)
root.right.left = TreeNode(2)
print(Solution().solve(root,-2)) # Find path from root to node -2
# I get the correct answer [3, 1, -2]
Copy by value
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param A : root node of tree
# @param B : integer
# @return a list of integers
def solve(self, A, B):
ans = []
self.f(A, B, [], ans)
return ans
def f(self, node, val, cur, ans):
if(node == None): return
cur.append(node.val)
if(node.val == val):
ans = cur[:] # Copy by value. Does not work!!!
return
self.f(node.left, val, cur, ans)
self.f(node.right, val, cur, ans)
cur.pop()
# Sample tree
root = TreeNode(3)
root.left = TreeNode(1)
root.right = TreeNode(4)
root.left.left = TreeNode(0)
root.left.right = TreeNode(-2)
root.right.left = TreeNode(2)
print(Solution().solve(root,-2)) # Find path from root to node -2
# I get an empty list []. Was expecting [3, 1, -2]
I tried copy.deepcopy()
as well, but that also does not work (I get an empty list).