This is the coding problem I'm doing right now in Python3:
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find_paths(root, targetSum):
allPaths = []
dfs(root, targetSum, [], allPaths)
return allPaths
def dfs(node, targetSum, currentPath, result):
if not node:
return
currentPath.append(node.val)
if node.val == targetSum:
if not node.left and not node.right:
result.append(list(currentPath))
else:
dfs(node.left, targetSum - node.val, currentPath, result)
dfs(node.right, targetSum - node.val, currentPath, result)
# backtrack here
del currentPath[-1]
def main():
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(4)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
required_sum = 23
print(find_paths(root, required_sum))
main()
The question is this line right here:
result.append(list(currentPath))
it prints out:
[[12, 7, 4], [12, 1, 10]]
but if you put:
result.append(currentPath)
it will print out:
[[], []]
I tried printing out the type of "currentPath" and it is already a list. Why is the list() necessary when it's already of type list?