I am writing a dfs function that returns all the paths to the leaf nodes.
4
/ \
9 0
/ \
1 5
Expected output for this list would be: [[4,9,5],[4,9,1],[4,0]]
This is what I have so far:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def leafNodePaths(self, root):
paths = []
self.dfs(root, [], paths)
print(paths)
def dfs(self, root, current_path, paths):
if not root:
return
current_path.append(root.val)
if not root.left and not root.right:
paths.append(current_path)
else:
self.dfs(root.left, current_path, paths)
self.dfs(root.right, current_path, paths)
The result I am getting is [[4, 9, 5, 1, 0], [4, 9, 5, 1, 0], [4, 9, 5, 1, 0]]
How do I keep accurate count of current_path
The hint is that you're passing the same list to your recursive calls, and then adding values to it. As someone once said, "shared mutable state is the root of all evils" (or something like that).
current_path is instantiated once, and every node adds itself to it as it goes. Then, when it hits a node, it adds a pointer to current path to the list of solution paths- so they each add a pointer to the SAME list.
Solve the problem with something along the lines of-
current_path = copy(current_path) + [root.val]