0

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

2
  • Please share a reproducible code, including your Nodes. Commented Jul 8, 2021 at 21:43
  • Updated. Trying to solve for this leetcode problem (leetcode.com/problems/binary-tree-paths) Commented Jul 8, 2021 at 21:48

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.