Check out a free preview of the full Four Semesters of Computer Science in 5 Hours, Part 2 course:
The "Depth-first Traversal Exercise" Lesson is part of the full, Four Semesters of Computer Science in 5 Hours, Part 2 course featured in this preview video. Here's what you'd learn in this lesson:

In the exercise you'll write a function that takes in a tree array and processes the tree into a flat array.

Get Unlimited Access Now

Transcript from the "Depth-first Traversal Exercise" Lesson

[00:00:00]
>> Brian Holt: So I am going to make you write it. So if we go to exercise here.
>> Brian Holt: I have three functions here. Preorder, inorder, and postorder. Here, I'm gonna very strongly recommend that you turn off the auto-run behavior, because this is going to be recursive. It doesn't have to be recursive, but I made it recursive, it makes it easier.

[00:00:31] And then go ahead and write these and then you can see down here the tree that I've created for you. I believe the tree that I gave you is, let me just make sure.
>> Brian Holt: Nope, it's not. Okay, never mind. Anyway, this is your tree right here.
>> Brian Holt: And then you can see here, this is what it is going to expect back from you.

[00:01:01] This is a valid binary search tree so your in order traversal will give you back a sorted list.
>> Brian Holt: Cool.
>> Brian Holt: So what you're going to do here is you're going to take in an array, the array will be given to you. And then each node you'll process differently, obviously.

[00:01:28]
>> Student: Can you describe the nodes specifically?
>> Brian Holt: Yeah, they just, they have a value and a left and a right.
>> Brian Holt: So every one of these is going to be called with this tree exactly.
>> Brian Holt: Actually, let's see if I look here.
>> Brian Holt: Yeah, in any case, so [COUGH] I want you to take this particular tree and then I want you to add every element in this tree to an array.

[00:02:08] And then these three will differ based on what order you add it to that array. Each one of these took me maybe five lines of code total, so just to give you an idea of the magnitude of code you should be writing,
>> Brian Holt: Let me make sure that's true before I truly surf it.

[00:02:30] Yeah, five lines of code each. So give or take ten lines of code, not take but give maybe. [LAUGH] Cool, I will give you, let's say, another 15 minutes to work on this. And then we'll talk about it and move on.