Log in from a computer to take this course

You'll need to log in from a computer to start Learn Data Structures and Algorithms with Python. But you can practice or keep up your coding streak with the Codecademy Go app. Download the app to get started.

apple storegoogle store
Learn

Now we have a recursive DFS function that also keeps track of the path as we search, but there’s one thing still remaining. We need to return the path! Let’s update our function one last time to output the path and complete our DFS algorithm.

Instructions

1.

We could modify our function to return the path in multiple ways. One simple thing we could do is have our function return a tuple of (found TreeNode, path tuple of TreeNodes). However, we know that the found TreeNode is always the last item of our path, so returning this object along with the path is redundant.

Instead, let’s change the method to only return the path. Modify the code in dfs() to return the path when a node with the target value is discovered.

2.

Now let’s run our algorithm and print the path found. We should see a list of Nodes printed to the console. The output should contain only the nodes in the path from the root to the target node. Experiment with your code by searching for other values in the tree. What happens if you search for a value that’s not in the tree?

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?