Today I spent some time on practicing coding. When I was trying to solve a problem about finding paths with elements whose sum equals to a specified value, given a binary tree and a value, I stumble against some unknown problems.
As I firstly finished my code, I got a null result. My codes at beginning was like this.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def FindPath(self, root, expectNumber):
if not root:
res = list()
path = list()
def SubFind(root, path, expectNumber):
# if root is leaf
if not root.left and not root.right and expectNumber == root.val:
# if root is not leaf
SubFind(root.left, path, expectNumber - root.val)
SubFind(root.right, path, expectNumber - root.val)
SubFind(root, , expectNumber)
Can you guys find where the problem lies?
Actually, the problem happens when I was trying to append a path to the res list followed by pop operation. You may better understand with the example below.
a, b = , 
print('Before pop:', a)
print('After pop:', a)
I bet now you must realize the appending here is about passing by reference. What is appended to the list
a is just a reference of list
b. When you modify the
b, the corresponding content in
a will also change.
In this way, I have to reassign another list and copy the content from b to this list. That is
path_cp = [i for i in path]
Finally, I got the correct answer.