Learn

To begin, let’s define our depth-first search function signature. We’ll start by writing a simple function to check if a provided tree node matches a given target value. If we have a match, then we return the node.

Instructions

1.

Within dfs.py, under the print() statement, define a new function dfs() which accepts two parameters:

  • the root node, let’s call it root
  • the value we’re searching for, let’s call it target

Start by having the new function simply return None.

2.

Now let’s modify our function to check if the provided root node matches our target value. If we have a match, then we should return the root node.

Before you return None, create an if statement that checks whether root.value is equal to target. Inside the indented if block, return the root object.

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?