1. Home
  2. Explore
  3. Computer Science
  4. Binary Tree Algorithms

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Binary Tree Algorithms

Transcript

binary tree is a common data structure  used in software development.   It's also a frequent topic and technical coding  interviews in this course, Alvin will explain   binary tree algorithms and prepare you to use  them in both interviews and coding projects.   Hey programmers, Hamilton from Shruthi, elk to  our course on binary trees, I want to show you   how you can do well on those technical interviews  that have binary tree problems. So what I have in store for this course, like usual, we'll go over  both the theory pines and binary tree algorithms,   as well as of course be more practical and come  up with a code implement those algorithms really   a one two punch. For every section, we're going to  be sure to draw out a pictures and visualize and   truly understand the algorithm on the whiteboard  notes are feeling comfortable with that,   we'll go over to the code implementation.  So in the description and in the timestamps,

you'll be able to find the corresponding exercise,  you can practice every algorithm that we go over.   In terms of the prerequisites for this  course, I'm going to assume that you're   not new to programming. And maybe you've dabbled  in some previous data structures and algorithms.   And you're also familiar with some recursion.  But that being said, I'm going to assume you know   nothing about binary trees, and even just trees in  general. with no further ado, let's jump right in. So first order of businesses, let's actually  understand what the word tree even means. And   like the programming concept, right. So when we  visualize a tree, a tree contains many nodes,   typically we draw nodes as circles, right. And  these nodes can also point to other nodes. So   here I have one node. And I could point to some  other node, right, I could point to any number of   nodes. So here are the circles, I'm going to refer  to them as nodes, and the lines or hours between

them, I'm going to call edges, right. So this is  an example of a tree. And trees can of course,   come in many different shapes and sizes. So here's  quite a large tree. Let's try to understand a few   terms we can use during our technical interviews.  And this is something I highly recommend, right?   helps if you speak the language, it does show  that you have proficiency dealing with the data structure, we could store values within the nodes  of our tree. For now I'm just going to put some   letters. When it comes to your programs, you can  store any type you want, you can store integers,   numbers, or even other objects. So because we have  a tree, we like to use familial relationships. In   other words, I think of like a family tree, right?  So if I look at node B, let's say I call them the

parent. If b is the parent, I know that children  of B are just the D nodes, right? their parent   and child is like a relative relationship. Let's  say I kind of changed my frame of reference. And   let's say I looked at a as the parent, well, that  scenario, then B and C are the children of a. for   the case of the C node, if I think of CSM parent,  it only has one child, its lone child being the F   node. So feel free to use that parent child  relationship when describing the relationship among nodes within a tree. Another terminal is  a lot in the context of trees is the word root,   right? So a root is going to be a node that has no  parent. So in this tree, A is the root because a   has no parent, right? There are no arrows going  into the a node. On the flip side of that,   if I look at the nodes in DNF, we call  them leaf nodes. A leaf node is a node   that has no children, right, so d and f have no  outgoing arrows. Typically, in a binary tree,

we're going to have a single root and we could  have many leaves. One thing I want to be sure to   do is make sure you generalize your understanding  of a leaf, right? So in this particular example,   looks like every leaf is two edges away from  the root, counting the number of arrows from   the roots, any leaf, it could be the case that  my leaves occur at different levels, right? So   I removed that F node, which case C is now a leaf,  right? Although a C is on like a different level than D and E, it's not the bottommost level, it  is the case that it's still a leaf, right? a leaf   node is just a node that has zero children. All  right. So with all of those terms out of the way,   let's hone in on the real topic here. Right,  I talked a lot about trees. But really in this   course, I want to go over the basics of binary  trees. Right? So let's look at that binary part   to begin with. That's really a dead giveaway.  We know binary has to do with the number two.

A binary tree is a tree where every node has at  most two children. Right? So currently on the   screen, I have a binary tree. If I gave a another  child, let's say a third node over here of f,   this would be a tree but not a binary tree. Right?  It would be like a ternary tree because I have at   most three children. So let's say I kind of remove  that extra node. Now it's back to a binary tree.   And it could be the case that a node has less  than two children but still be a binary tree, right? So if I gave C, just a child of f, this is  still a binary tree. It's if I look at any node   within my tree, that node will have 01 or two  children, and no one has more than two children,   right? So you want to be sure to remember that  a node in a binary tree could have less than   two children. All right. So I'll be the first  criteria for understanding what a binary tree   is right? It's probably the easiest criteria and  most children per node will also want to be sure

to add into our definition Have a robust  understanding is to also remember that,   at least for us in computer science, we think  of our binary trees as having exactly one root,   meaning there should be only a single node that  has no parent, right? Typically when we draw,   it would be like the topmost node. So right  now this is definitely so far a binary tree.   If I had some other node in this drawing,  like G, right, g also has no parents, I would no longer consider this a classic  binary tree, right? So watch out for that.

Let's go on to our final criteria, we also need  one more ingredient. And that's exactly one path   between the root and any node, right. So looking  at my example to the left, this is indeed a binary   tree that meets all three criteria. And let's say  I chose the root and any node, obviously, there's   only one root, so we're definitely considering the  a node, let's say I chose some random node like E,   this is really a binary tree, then we're  guaranteed to have only a single path that connects A to E, a path is really just a series  of connected nodes I can travel through, right,   so to get from the root a to the node E, I  can go from A to B to E, and that would be   one path. And that's the only way to get from  A to E. That's what I mean by exactly one path.   Let's say I chose another node like F. There is  also exactly one way to get from the root to F,   and that's just a CF, that would be the only path.  If I added some additional connections or edges

within my tree, I can get a scenario like this,  this would no longer be a binary tree. For one,   we can see that B has three children, but also  does not have a unique path between the route   in any node. For example, if I chose a and the  note of f, one way to get there is by going ACF.   But another way to get there would be a, b, c, f,  right? And so do watch out for all three criteria   when you're considering a binary tree. Awesome. So  let's look at some smaller examples. And this is where I think some students tend to struggle with  their understanding of binary trees. So if I took   out some nodes over here, this would definitely  still be a binary tree, right? Just looking at our   different rules, right? Let's say the root node A  only had one child would still be a binary tree,   right? Because the binary tree only demands that  we have at most two children, we still have one

root, and we still have only one path from root  to any node. Let's say I have the smallest tree   that has a node, which would be the singleton  tree, this is still considered a binary tree,   right has one route. And there's not really any  pass to be had here except the route to itself.   And every node does have at most two  children. Here we have zero children, right?   The final edge case we want to think about  is what happens when we have no nodes, right? We consider this as the empty tree. This  is a very special case. And we should consider   any empty tree as actually being a binary tree.  That's going to be very useful when we come up   with some algorithms later on, right. So a common  edge case off to consider is what happens when we   have an empty tree, that's a tree with zero  nodes, right? Let's look at another example.   Let's say I had this structure to take a moment  look at it, and see if this meets our criteria.

This would not be considered a binary tree. So  we look at your different criteria. Looking at   the first one, it does have at most two children  per node, so that's okay. But we can't identify   exactly one root here. Remember that a root  node is a node that has no parent, right?   If you look at every node in this picture, every  node has exactly one ingoing arrow. So that means   every node has at least one parent,  right? So it doesn't meet that criteria. And furthermore, there is not exactly  one path between the root and any node,   because we have a cycle within the structure.  So for example, let's say I was starting at a   right and I wanted to travel to see, one  way to get there would be to go A, B, C,   that'd be one path. But I could also have another  path or I just go around twice and go A, B, C,   again, there would actually be an infinite number  of paths in this scenario. Because of that, this

is definitely not a binary tree. And there kind  of many reasons for that. If I had a different   example, looking at this one, now I need criteria  one and two, right, I have at most two children   for every node. But I also still have exactly  one root node here I would consider z the root   node. However, there is not one path between the  roots in any node and because I have that cycle. So these rules are really worth remembering,  they're really going to help you solve a much   more difficult binary tree problems. And if you  remember these three rules, you can identify   different problems in a binary tree framework.  In other words, the hardest problems that you'll   encounter in your interviews are problems  where they don't tell you straight up what   data structure you're dealing with, you're just  gonna have to notice the pattern. In other words, what if I gave you some structure like this, take  a moment and figure out if this is a binary tree.

If you look closely, this does meet all  of the three criteria to be a binary tree.   I can just treat a as the root because it has no  parent. I can treat nodes D and F as the leaves   because they have no children. I just drew  this in a pretty interesting way. Right? If   you really range things in a classical binary tree  sense would look like this. More importantly, this   has the same relationships as a previous drawing,  I just show it in a top down fashion, right? So no matter what do you understand these three rules  for a binary tree, right? Because sometimes may   not be as explicit as a nice triangular shaped  drawing. Awesome. So we've talked a lot about the   theory of how to, you know, look at and reason  through some binary tree definitions. Let's   go ahead and start to talk about how we could  represent binary tree programmatically. In other   words, how can we do this in some code? Well,  no matter your programming language of choice,

I think you're going to represent these as  objects. In other words, every node here is   going to be some objects. So it could be like an  instance of a class, the properties only to store   within this object would be the current value. So  I need something to store like the A of my current   node. But I also need to refer to some children.  So we'll also need some left and right pointers   to the children, right, those are just going to  be some properties on that object. In a classic binary tree is very common to refer to the  two children using a left and right direction.   Notice that some nodes here, like the C node,  they're only going to have one child, right? c   only has a node dot, right? It does not have a  left. So we're gonna have to use some empty value,   like null or undefined. To represent a child that  doesn't exist, right? Especially for a node like   he, he has no left and also no, right. So here's  what we'll do, let's go ahead and hop into my text

editor. And I'll show you how you could represent  a binary tree programmatically. So transition,   here we are in my text editor. Let's start by  creating our node class, right. So you'll be able   to follow along any language that you choose,  I'm going to do mine in JavaScript, right. So   I think the best way to present a node is just  to use some class. So hopefully familiar with   some classic class syntax, let's create a node  class, there's going to be a quick constructor, I think would be valuable to take in the initial  value that's going to be stored within the notes,   I'll take the ns a constructor argument, I can  just set this dot Val to that value, and also need   two more properties, one for my left, so I can say  this dot left, I'm gonna initialize it to null,   that means by default, a node will have no left  child the same way. By default, a node will have   no right child, right? So when you use no to  represent children that don't exist over here,

awesome. That's all you need to create, you know,  a baseline binary tree, right, we're going to use   this class a lot during the course to test our  algorithms. So I'm going to create a node and   eventually wire up a tree. Well, I'll just call  my constructor few times, I'll create different   nodes, I'll just store them to some variable  names. And of course, a new node to create   new instance of node, and I'll store some value  inside, I'm going to store some characters inside, I'll create a bunch of these different nodes,  what we'll want to be sure to do is make sure   that you also set their pointers properly. So  I'll give each of these some different values ABC,   D, E, also do F. And then I'll just manually  for now set their pointers properly.   So what if I did syntax like this is since I'm in  JavaScript, I can easily assign these pointers,   I can say, A's left is going to be B. I can  say A's right? is C can also say B's left D.

and then B's right is E. And maybe Finally I can  say C's right is F. So by doing these assignments,   I'm connecting some nodes together, I should  end up with a structure like this right? Have   a as a root, because nothing points to a  it has no parent. But a has two children   of the NC. And then along with  that, B has two children of D and E. Finally, C just has a right child of f, this is  actually the same tree that we looked at a lot   during the whiteboard session, right? And  that's how you can represent that same tree   programmatically, right? So I always think it's  valuable to also try to visualize your trees,   right? Obviously, we created this tree in a very  manual way, probably in the long run will create   applications to just maintain and create trees  dynamically during some input. But for now,

we'll start by creating all of our  trees in this very kind of static way.   Right? And so with that, now that we have an  understanding of how to represent a binary tree,   let's go head back to the whiteboard. And  I can show us our very first algorithm. Hey, programmers, Alvin here, right? Now I want  to go over this depth first values problem.   So this will be a good review of the depth first  traversal algorithm. So what do you want to do in   this problem? Well, what we want to do is take in  a binary tree, and in particular, your function is   going to take in the root of the binary tree.  And just recall that given the root node of a   binary tree, we know that that node is going to  have pointers to its left and right children,

which may point to other nodes. However, if let's  say a node does not have left or right child, then   its point is going to be set to No. So that's how  I represent our binary tree programmatically. But   for now, let's just stick to the visual represent  of our tree. So for a depth first traversal,   we could start with the root node of a, what we'll  do is we'll just add that to some collection.   And we're going to have to maintain these in  a very particular order. And then from there, according to a depth first traversal, I could  go to B. And here's where we make our really   important decision, right, we can either go to  C, or D, if I'm doing a depth first traversal,   I need to go deeper in the tree before I move  laterally. So that means I go from B to D.

And once I bought them out at D, there's  nowhere deeper, I can go from D. And so now   I move laterally to the E node. And this pattern  continues, right? I don't have anything deeper   from E. So now I go to C. And then from C, I go  to f. So this would be a depth first traversal   on this binary tree. Notice that it goes A,  B, D, E, C, F, and again, the really important   characteristic is we must go deeper in the tree  until we can't anymore and then we can go across the tree. That being said, How can we actually  managed to implement this algorithm. If you're   familiar with depth first, traditionally, then we  know that it's going to use a data structure like   a stack. So let's get situated over here. So we'll  trace through that again. But this time, taking   a really close look at how we can use a stack to  accomplish that direct order. And so just recall

that a stack is a sequential data structure where  we can only add things to the top of the stack   and remove things from the top of the stack.  So a really important characteristic is   we can't really insert or remove elements from  anywhere but the top of the stack. So when I add   things to the stack, I was added to the top like  this. When I remove things, it's also from the top   like this. Alright, so when I begin at this  depth first traversal algorithm, I'm going to start with the root node of a. And by default, I  really just take that root node and I just store   it on my stack. So it's the only thing on my stack  right now, I'll use these rectangles represent my   different stack frames. And really in my program,  that would just mean storing the actual instance   of node or some pointer to it. Cool. And then  from there, I actually begin my main algorithm.

So the main flow of a depth first traversal, we'll  check if the stack is empty. Right now the stack   is not empty, because I have at least one element.  And so what I do is I start by removing or popping   the top element of my stack. So I'm gonna remove  the A, and I'll label that as my current node   being explored. And when something leaves the  stack, then I can consider it being visited right   now. So I need to list out my values, because  that's the whole point of this problem, right? So by now I've just visited the a node. At this  point, I can look at that nodes children now.   So I look at the a node in the tree, and I see  that it has a B child on its left and a C child on   its right. And from there, I push or add those two  children to my stack. So I'm going to put c first,   and I put B afterwards. And notice if I push my  right child first, followed by my left child,   that makes it such that my left child is  at the top of my stack, which means that

I would hit them next. And that actually ends on  my first iteration of this depth first traversal.   And now I asked that same question is my stack  empty, it's not. So I removed the top of my stack,   I'll call it B, my current, which means I could  print it out or insert it into my values list.   Nice. From there, I consider B's children,  B has two children. So I add them both,   I push E, followed by pushing D. That ends that  iteration. Now something interesting happens, my stack is still not empty. So I know I removed  the top, so I call D, my current, I add D to my   list of values. But if I look at these children,  it actually has no children, right, and so there's   nothing to add to the stack from here. And  so technically, I finished this iteration.

And now I still have stuff on my stack. So now  I pop he off the top of my stack. Same thing   as before, right, I add to my values, he has  no children. So I'm done with that iteration.   Finally FC, I removed C from the stack, and I  printed out in my values. And then at this point,   I see that the C node only has one child, so I'm  just going to push the children that exists so I   would push the F node onto my stack. And that's  a really important thing to remember when it comes to implementing your depth first traversal  you're going to have to check if your children   exist before you add them to your stack. And now  on the final final iteration, we have the F node   we remove it from the stack, we add it to our  list of values f has no children. And so I finish   this iteration and now my stack is empty and I  will just exit right once the stack is empty. I   know that I must have traveled through the entire  binary tree. So there we have it and we do get the

correct output over here. So just by using a stack  and just obeying the rules of the stack, that is   we got pushed to the top and removed from the top  we will get the correct order. important thing to   remember is you should add your values into your  like values list whenever something leaves the   stack. That being said, What can we say about the  time and space complexity of this algorithm? Well, it's actually pretty straightforward. Let's say  we define n as the number of nodes in this binary   tree, then we can say that the time complexity of  this is O of n. And why do I say that? Well, we're   just going to add that every node eventually to  our stack. And that nodes also going to leave the   stack exactly once. So it's not like we're double  visiting any of the nodes. So I'm guaranteed to

just run in O of n steps. In a similar way, we  can see that the space complexity is O of n,   the only thing we stored was really the  stack, which is a linear data structure.   And we know that we're not going to put ever  more than n things on the stack. So overall,   we have a linear time and space solution for  this depth first traversal problem. All right,   I think we have a good understanding about the  approach for a depth first traversal. Now let's go ahead to the walkthrough video. And we'll  implement this one in a few ways together. Hey,   programmers, Alvin here, right. And I want to go  over a JavaScript solution for this depth first   values problem. And so we're going to do here is  really just implement that same strategy that we   traced through in the approach video, pretty much  to the tee. And we'll start with the iterative   version. And that means of course, we will solve  this one in two different ways, right, we're gonna

solve it iteratively first, and afterwards,  we'll go ahead and solve it recursively.   Alright, so let's jump right in over here. Like  we said, in the approach video, we know that the   iterative version really relies on us creating a  stack. And for most of your programming languages,   you can just go ahead and use your like array  data structure for that. So I'm going to use   just a plain old JavaScript array, I'll go ahead  and name this one stack. And we can just use an array to represent a stack as long as we stick  to two particular methods, right, I'm going to use   array push, which adds to the end of an array,  and also array pop, which removes from the end   of the array as well. So I'm going to consider the  end of my array to represent the top of my stack.   Cool, we'll go ahead and do is initialize  the stack with the root node on top of it.   Nice, then I can have my main loop for the  algorithm. So we know that we need to keep

running the algorithm while there's stuff on our  stack. So I can just check while stack dot length   is greater than zero. So while I have  at least one element on my stack,   there is some work to be done here. And that will  step through a single iteration of this algorithm,   we know that we start interation by just  removing the top of our stack, in other words,   stack dot pop in JavaScript, that will also return  us the element that we just removed. So I'll call that my current const current. And that is going  to be an instance of nodes, it's going to be   one of these objects. Cool. So now that I  remove this element from the top of my stack,   let's say for now, I just I don't know,  print it out, maybe we'll kind of debug   this one as we go. So console dot log, current  dot Val, because I know that every instance of   node has a dot Val prop on the inside. And then  from there, I need to add this nodes children.

So you might go ahead and guess that to do that,  we could just do stacked up push, I'm going to   push the left child, one out here, so node or  current dot left, followed by the right child. But we also need to make sure that these  children exist, right? Look at the prompt.   There could be instances, for example,  like this C node over here, this C node   only has a right child, but has no left child,  right. So what I don't want to do is push C's   left, because that'd be pushing no onto my  stack, which would give me an error later   on. Right? So I want to only push the children  if they exist. And I need to individually check

if the left exists and push it and also if the  right exists and push it, I'm just going to   add some guard statements for both of these. So  we'll go ahead and insert will say, all right,   if the current has a left and right side, current  dot left, called justice for the right hand side, cool, maybe we can inline this, if you prefer.  Alright, so I'm going to only push the children   if they exist. And that should actually be the  heart of our depth first algorithm. So we're not   putting our values inside of an array like the  problem asks, but we should at least be able to   see the correct order of printing here, because  I'm going to print a nodes value as soon as it   is removed from my stack. So I'll go ahead and  actually maybe bring in maybe one literal test case, so I could just steal this little stub over  here. And this will just print out the values.

Right, so I'll test this I can hit Run, if  I hit Run, it's just going to execute this   file just like a script. So it's not  going to run any automatic test cases,   just going to run my file as is. So if you want  to test it in this way, kind of in a manual way,   you're gonna have to be sure to call your  function. I do have a console dot log on   the inside. So I'll just run Run this manually.  And when I do that should see some output here looks like node is not defined because I forgot  to bring in my class definition. So I'll do that.

give that a go. Alright, so looking at our output,  we didn't get our exact depth first traversal,   like we expected, right? I got ACF, B, D, if  you take a look at what we really printed out,   we technically did print out a depth first print,  but we favored the right hand side. So we did a,   c, f, and then B, E, D. So let's say we really  wanted the left to right version of this,   and all you have to do is flip the order that you  push the children, right, it should be clear by looking at these two lines, right? When I add  my children looks like I push the left child,   and then the right child. If you push the left  child first, and then you push the right child   afterwards, that means that the right child's  going to be on top for the next iteration. So   if you do it like this, this will favor the  right hand side and travel through it first.   But if you did it like this, now you'd be  actually iterating to the left branch first,

toward the right. So with that small change,  let's just see what our print is. And there   we have a nice AB de ECF. However, in this  problem, they want us to actually return   those values in an array. So I can kind of  get rid of this little Manual Test over here,   I don't need this class definition anymore. And  now instead, I'll just gather up all of my values   in some results array. So I'll say, maybe result  over here starts as an empty array. And then as I pop elements from the top of my stack,  instead of logging them, I'll go ahead and do   result dot push, and I'll push that value into the  result array. Once I'm done with this while loop,   that means my entire tree has been explored. which  case I can return, make sure I spell it right,   return my results. Cool. So this should be a  nice solution, it's actually run the test cases   on this. give that a go. So it looks like we're  doing pretty good. But for this very last example,

looks like we're getting can't read property  Val of na, and that's running test case 04.   So if you actually go into the prompt, those  test cases are actually laid out explicitly   over here. So I want to go to zero for now  let's look at the zero for test case. They go   ahead and they pass my function, no, right kind  of representing like an empty tree or an empty   node. And we can kind of trace it what happens  here for our code. Let's say that root was null. That means when we initialize our stack, our stack  literally contains like a null value. So it's not   even an instance of note just now. So that means  when I entered this while we're going to check,   you know, Do I have anything in my stack, and  I do because my stack length is one. And then   when I pop, the top element of my stack current  is going to be no, then on this line 14 it says   null dot Val. And that's actually where our  code explodes, right on line 14, right? You

can't reference property Val, of null. And so  to handle this scenario, we want to make sure   that we actually never allow anything No, to enter  the stack. It's kind of why we had this guard over   here. mentioned also be true for even the top  level route, in case they give us the empty tree.   kind of seems like a corny, you know edge case.  But this is a pretty common one, when you actually   go into your interviews, right? What  happens if you have an empty input. And so I'll just guard that explicitly,  I'll go ahead and check, hey, if my route,   so if my entire tree is empty. So if route equals  null, then what I'll do is just return an empty   array, right? Because that means there are no  values inside of it. And that actually is the   expected answer, according to this, right should  return an empty array. So let's give it a go now

should be pretty good. Nice. And there,  we have our nice iterative solution for   this depth first values problem. Alright, so  here's what we'll do. That was one solution.   Let me show you another way. let's implement  this. And that would be our recursive flavor.   So I'll just kind of redefine it down below. And  I actually recommend practicing both versions,   because they're going to serve as like the  basis for which you solve a lot of different tree problems. And so when I think about the  recursive version, like all of our recursive code,   I must think about the simplest case of my  input, and that will act as my base case, right?   So in the case of a binary tree, the simplest  tree you can be given is going to be the empty   tree or just a no root, right? So it's not even  going to be about a node that's single node right   inside of a binary tree. It's going to be about  an empty tree, right, a tree with zero nodes. I'm

going to check if my route is no, and I have an  empty tree. And I think about this base case, as   if it's its own input, because it really is right  and so if someone They asked me to give them back   in array of all the values in the empty tree, it's  still the case that this must be an empty array,   right? Because there are no values,  there's even any nodes and the empty tree.   And then from there, I can generate my actual  recursive call, right. And I know what I call my stuff recursively. That means I have to  reference a function and again, go ahead and   invoke it. And I'm going to call upon root dot  left, as well as root dot, right? So this would,   this call over here would give me back an array  containing all of the values in the left subtree.   And this will give me an array of all the values  in the right subtree. And so let's say I see these   into their own variables respectively, you don't  have to do this part. But I'm kind of a fan of it,

especially if it's the first time implementing  this. So I'll call this my left values.   I'll call this one my right values. And here's how  I'm able to kind of quickly create recursive codes   all about taking when I call is a recursive leap  of faith here. So let's say we're stepping through test 00. And so this is our tree visual, right?  So we know that our root is going to be a node.   So when I actually make this top level call,  this base case does not fire. And so I make my   recursive calls, right? I know when I do depth  first value, or values, rather, let me fix that   depth first values of root dot left, that means  I'm going to be passing in the B node, right,   and here's how I have to actually pretend my code  behaves, I'm just going to get back the correct

result from this call, right? So if I passed  in the B node into this call, what I expect   back is the full array representing the depth  first traversal of that subtree, starting at B,   right. So if I got correct data over here,  what it would look like is just B, D, and E. That would actually be the full depth  first traversal, from this subtree,   right. And I'm kind of doing that just mentally,  or I know the expectation for this algorithm,   it's going to be a similar story for my right  call, right? If I'm at a So A is still my route,   and I passed in my right child See,  to this call, what I expect back   is just an array of CF, which would be the  depth first traversal of that left subtree.

And now that I have, you know, my left subtree  values and my right subtree values, I have to   think about how to combine it all together, right?  How do I work myself into that output by combining   both of the results from my children, right, what  I need to do is really just take myself put it in   the array, followed by my left children, followed  by my right children. So I can do some nice   JavaScript syntax for that whenever returning  the right when I throw myself in there, so I'm going to throw in a root dot Val, that's myself.  So that'd be like the a node that I just take all   the values in my left result, put them in here and  just use the spread operator to unpack that array.   And I'll do the same thing for the right values  of CF, right. So dot dot, dot, spread out right   values just so I return a single array, and this  pattern itself does match this output, right,

kind of taking the leap of faith and assuming  correctness from these recursive calls over here,   right, I have a, and I plug in substitute B, D, E,  and then for the right, I have CF. And even before   we run this, I'm not going to, you know, assume  too much JavaScript knowledge. So maybe you're   kind of new to this spread operator. So  in general, super quick aside over here,   let's say had an array of some stuff. So I'll  say, peeps there and some people over here. So we'll throw in fleabay, we'll throw in Jason,  throw in Raj, throw in heavy. And what I can do is   whenever I have an array, I can just use a spread  operator to kind of unpack that array. So for   example, I can say const will say new peeps. And  I'll create a new literal array. So whenever I say   square brackets, it gives me a new array  literal. And what I'll do is, I don't know,   put an element at the front, we'll call it Alvin.  That'll spread out the elements of peeps, right?

So just imagine I took all of the elements here  and just remove the brackets. That way I don't add   any initial nesting. And then at the end, I don't  know I can add someone else. Like, right? Well,   console dot log, what new peeps looks like so I'm  not gonna run the test cases, we're just gonna run   this file as a script, just so we can review this  spreads index. So if I give that a go, we kind of make this bigger. Notice that I have correctly  spread things out right? Have Alvin at the front,   and I have all of the things from peeps in the  middle, right, followed by Brian at the end.   So you can do this. You can also use like the  concat method on arrays. You're probably going   to see me use this spread syntax a lot because  I'm kind of a fan, right. But with that in mind,   let's go ahead and actually test this code. So  we'll run all the test cases. Nice. And this

is another working solution for our depth first  values. And it should be pretty natural that we   can solve this problem also recursively. So I know  that the iterative solution for this depth first   traversal requires a stack data structure.  And I know whenever I write recursive code,   under the hood, your programming language is  actually going to track all those recursive calls,   using the call stack, right? That call stack  behavior gives you the same type of ordering, which is really convenient. Cool. All right.  So before I send you off on the next problem,   I want you to actually practice both solutions  for this depth first values code, it's going to be   very necessary to actually master some later  concepts that are coming right up. So do spend   some time on this practice makes perfect,  right, and I'll catch you in the next one.

Hey, programmers, Alan here, right? Now I want to  go over this breadth first values problem. So it's   really just going to be a little variation off of  the depth first one we just did, of course, but   it's really important that moving forward for all  of our tree algorithms and other data structures,   that we have both versions down pat. So in this  problem, we're going to take in a binary tree, once again, very classic binary tree structure,  this time, I want to return an array or a list   of all the values according to a breadth first  traversal order. So a breadth first traversal   starts with the root node of a, so that's  nothing new. And then from there, I could   go to B. So right now I have my a node, and also  my B node. And here is where we diverged from our   previous problem in a breadth first traversal. And  breadth just refers to like the width of something

I travel across before I go deeper. So in our  breadth first traversal, I'm gonna move to C   and not D for now. So I add my C node c value to  my list. And then from here, once I finished this   entire level, and there's nowhere to go across  the tree anymore, now I could go downward to the   next level. Now I have D, and then E, and then F.  So they're really important distinction here is   the breadth first traversal starts with  ABC, whereas the depth first traversal would have started A, B, D. That's a  really, really important distinction.   And so how can we go about implementing  the breadth first version of this?   Well recall that the depth first used a stack  data structure, well is the case that the   breadth first is now going to use the queue data  structure, really just the partnering version   of that structure. And so let's kind of step  through that in a more programmatic way. So I'm

going to use and track my queue. And just recall  that a queue has no sense of direction to have   the back of my queue and the front of my queue,  things enter the back of the queue, and they leave   the front of the queue. Right. And so no one gets  a skip line either. So this gives me a nice fair   ordering, think of a queue as just like waiting in  line at checkout at a grocery store or something.   So how do I begin my algorithm, I'm going  to start by initializing my queue with the root node. So I'm just gonna start with a on my  queue. And then from here, now I can begin my main   algorithm. So my main algorithm should check  on every iteration is my queue empty, right now   it's not because I have at least one element.  And so I remove the front element of my queue.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent