CS 203 LECTURE 14 Breadth First Traversal of

CS 203 LECTURE 14

Breadth First Traversal of a Binary Tree Breadth First Search is not a wise way to find a particular element in a binary search tree, since it does not take advantage of the (log n) binary search we can get in a well-balanced tree. However, the term is often used loosely to describe breadth-first traversal of an entire data structure. The most likely actual use case for BFS with a BST is to test whether your trees are being constructed correctly. Lab 9 will include a method to do a BFS of your Binary Search Tree. Here is the algorithm: • Create a permanent queue to hold all elements. • Create another, temporary queue to hold elements that you are processing to find the BFS order. • Add the root to the temporary queue. • As long as there are node references in the temporary queue, poll them one at a time, add them to the permanent queue, and add any left or right references to the temporary queue • When the last node is polled from the temporary queue, the permanent list is complete. 2

Breadth First Traversal 1) Create a queue for unvisited nodes and a list for visited nodes 2) Put the starting node at the back of the queue. 3) While the queue is not empty: 1) Take the front item of the queue and add it to the visited list. 2) Create a list of that nodes neighbors nodes. Add those which have not already been visited to the back of the queue. The next two slides show BF traversal of a graph. Think about how to do this with a BST. This slide and the next two use material from https: //www. programiz. com/dsa/graphbfs

Breadth First Traversal

Breadth First Traversal

Quick-Sort 7 4 9 6 2 2 4 6 7 9 4 2 2 4 2 2 7 9 9 9 Quick-Sort
- Slides: 6