Breadth First Traversal

Loony Corn
A free video tutorial from Loony Corn
An ex-Google, Stanford and Flipkart team
4.2 instructor rating • 73 courses • 129,216 students

Lecture description

Traversing a binary tree can be done in variety of ways. The breadth first traversal visits and processes nodes at every level before moving on to the next. Let's visualize breadth first traversal and see how it's implemented.

Learn more from the full course

From 0 to 1: Data Structures & Algorithms in Java

Learn so you can see it with your eyes closed

14:58:54 of on-demand video • Updated April 2019

  • Visualise - really vividly imagine - the common data structures, and the algorithms applied to them
  • Pick the correct tool for the job - correctly identify which data structure or algorithm makes sense in a particular situation
  • Calculate the time and space complexity of code - really understand the nuances of the performance aspects of code
English [Auto] Know one of the most interesting things do with trees is to visit and process all of it. But I believe in which this can be done visiting and passing notes that tree is gone. There are two packs of covers. But first and last in this lecture we began to look at how their first trial was we've just learned about the structure of a binary tree. Now let's hear about the things that are actually interesting about the binary tree. In the case of a Q and A Stack what was interesting from a user perspective is the behavior of a Q and A stack. When we pushed and popped elements of the cube and the good elements in the gaze of a binary tree what is really interesting about it is how the nodes of a binary tree can be visited and processed this is binary tree traverses binary tree traversal can be done in a whole variety of ways and they are very interesting because they lend themselves to interesting problem solutions. So what's really about interesting about binary trees is that number of ways in which we can visit the nodes of a tree. So what's different about the different ways that we visit the nodes. How big is it the north of a tree can vary based on the order in which the nodes are accessed the we visit the nodes and give rise to a different sequence of node IDs based on the order in which we access them. These different or those in which we access trees give rise to different algorithms which find different use cases in the real world. And they're solving problems. That is why it's interesting to study these algorithms by which we visit all the notes of a tree in a different order. Visiting them in order for free and processing these nodes it's it's. But I think the there is a subtlety here. I spoke about visiting earlier but what I really meant what we process the notion of a tree in all the algorithms that we see so from now on we notice that we might visit a node more than once but process a node exactly once it's the order of processing that's important. And I'm using visiting as a substitute for processing and it's important to realize this difference because it's the processing of the north that really matters. It's possible to access a third node the process that you have to go through the second node node when it's processed that is the important operations that anybody about. So getting back to what we are talking about processing the order for three visiting them and processing them is all that I will think or the. And there are 0 mean bees in which it can be done. The first is oil. Brant first breadth first essentially means that you visit on loads of a level before moving on to the level next level. All nodes at the level formed the breadth of a tree. So we access every node in the break first before moving on to the next level. This is called breadth first traversal of a tree the other broad category of tree traversal is called breakfast. This means we reach into a tree as deep as possible get to a leaf and process that how we go deep into the tree. That's another question for a little lecture. We'll be talking about breadth first traversal baby access all nodes in a particular level. Before moving on don't worry before the binary tree is out we have spoken in detail about both. But first algorithms as far less direct first algorithms Let's first take a look at how breadth first traversal of the tree works best for us in was visiting all nodes at a certain level. The we move on to the next level. All nodes at a certain level have to be visited and processed before the algorithm can move on to processing nodes at the next level. If you go back and remember all the tomes we learn about a binary tree we spoke about nodes at a level being siblings. So all siblings have to be processed before moving on to the next set of siblings at the next level. So what nor do we stop it. Typically all algorithms which will travel seeing a tree or in a tree in generally starts with the root node the root node is the one node using which we can access all elements of a tree. All nodes of a tree are accessible from the node. So even for breakfast traversal we start with the root node the root node is at a level a zero. And if the first node that we visit and process going back to our levels remember that the level basically defined the distance from the root node nodes that level 1 or one hop away from the root node nodes that level 2 are two hops away from the root. Since the root node is zero hops away from itself it is said to be at level zero Obviously once the root node is done we check to see if there are any other nodes at that level. And visit and process them. Obviously the root node is the only node levels. That's just the structure of the tree. So once we process the root node we move on to its children which are at a level 1 they can be at the most to know that level 1. We have to process both of those nodes and only one if there's just one order in the block is late. But we have to process both of those nodes at level 1 before we can move on to the nodes at level 2 to process them. Once we are completely satisfied that the level has been exhausted and there are no other nodes to visit and process at a certain level then there's when we move on to the next level. So if both children of the route have been processed or however many children it has has been processed then we can move on to level 2 and process all the nodes deep. And then you add this in every node of the tree has been visited traversal in was visiting and processing every node of a tree. So we continue this breakfast drive. That is with us and that is visiting and processing every node at a certain level. We keep moving up levels every node of the tree has been visited all this will stock. Let's see how that first Trevathan are books. And let's see it in a visual B that you can really understand what's going on. Let's look at how Bedford-Stuyvesant sell books rather than just talking about it. So here we have a binary tree. We're going to be working with this tree a lot. So you'll see a lot more of it in the coming years. What is the art that Bret first from us ekes Binoy it starts with the root node which is the flow down to the left and move sideways and flow down to the left again sideways. Slow down to the left and move sideways. Note that it completes visiting all nodes at a certain level before it moves on to nodes at the next level. So B and C which are at level 1 are visited one after the other. Only after C is complete. We move on to the after becomes easy and then we move on to the north at the next level which includes F which is a child of B. That doesn't matter. It's the North that the same level which matter. So the process level in before moving onto level and plus 1 and plus 2 and then finally we end at the highest level which in this example is level 3 restocked with it being gnawed at the food which means we start at Naude the. So let's visit nor eat. Now there are no other nodes at the same level of eat because it's not nor. If the next node that we have to visit Nordie is at level 1. One thing to notice here is that we typically visit nodes which are left before nodes at the right. So we move from left to right for the nodes which are at the same level the is the left most normal at level 1 which is why we visit the next used the green color to denote nodes which we've already visited and processed. So he is marked in the next node has to be at the same level. The only option here is the at the bottom right we keep a tally of the nodes we've already visited and processed. So far we've just got it in the list. We visit seat 3 is the next level one and we see now that there are no other no that level. We can now move on to the next level. Remember that we go to the left most node and the next level first so the Nordie visit between D and E is the the more we visited so far are in B. So we're keeping a track at the bottom. Let's go on and visit the. All right. He is at level 2 and is the first note that we visit at levels to the left most not. Now it's time for us to continue with this breakfast search and the next note we'll visit will be the nodes we've seen so far in order of R E A B and C B keeping track at the bottom we visit ABC and the other nodes that we've seen so far. It's time to move on to the next level. And the left most normal is if it's that level 3 in this binary tree nodes we've seen so far ABC and eat in that order. In breakfast travel through the next we visit if h. There's just one note left it if the right child of each note that we've completely ignored who the parent nodes are. When we do Bedford-Stuyvesant we only look at sibling nodes and move from one sibling node to another. Finally we visit G. This is the last node in our list. We've seen all nodes through to age and we are currently processing G are very troublesome in a bet. First man is now complete. He showed us the final order in which we visited the notes A B C D E F H G. Now that we visualized that first travel cell and know exactly the path that it takes to treat let go about implementing it. The algorithm involves starting from the root. We use a view here. Yes we use some of the data structures we're already familiar with because it lends itself very well to the problem to be solved. What we want. In the case of Brett first traversal is that the node added first to the queue should be the first to be killed it just right a few books. We add the root node to the queue and then set up a loop to basically process nodes from the key of the queue and process the node which will initially be level. After we've processed it. The IDE it's children to the queue making sure we add the left child first adding the left child first is important so that we traverse the siblings from the left to the right. We continue this process so long as the queue is not empty. If you sit down and think about it and maybe book it out with and then people you'll notice that the notes get added level vice from left to right to the cue at the root node and then its left child and right. And we process the left child we add its left child and the right and we continue this. This means the nodes get added level rise from left to right to the key. This also means that the nodes are being viewed and processed in the order from the left to right. I note that the same level would be exhausted first. Work it out with a pen and paper. You'll see that it works out perfectly. Let's see what the goal for breakfast Ramilison looks like. We use a cue that we did earlier in some of our lectures look at the code onscreen screen. The very first thing we check is that the root of the tree that we lost been passed in is not not a null route basically means that there's nothing to traverse. We simply return. There is no breakfast for us. Also note that this is an iterative and that it is not recursive we simply push and do things and begin them all in of-I we start up by setting up a queue holding nodes and undo the rule. We know the root is a valid value it's not null. So we do the root. We set up a while loop which processes the nodes in the queue. So long as the queue is not empty when we kick it off we have the root node present in the queue. So we end this way within the while loop we process the head of the queue we need. Q The first element of processing is basically just a print statement. We are just printing it discrete and then we add the left child followed by the right child. We Intuit on the this ordering is important so that the next level it gets processed from the left most nodes first to add its left child and right child to the key. So we are filling up the queue and we are checking that it's not empty and processing all logs. Then there are no more children to process. The queue will be empty. We will have processed the last node in the tree.