Breadth First Search or BFS for a Graph. For simplicity, it is assumed that all vertices are reachable from the starting vertex. For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. The code for the Breadth First Search Algorithm with an example is shown below. The code has been simplified so that we can focus on the algorithm rather than other details.
I was trying to solve one interview question, but for that I have to travel the binary tree level by level. I have designed BinaryNode with having below variable
Could someone please help to write the BreadthFirstSearch method inside my BinarySearchTree class?
Update: Thanks everyone for your inputs. So this was the interview question.'Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (i.e., if you have a tree with depth D, you’ll have D linked lists)'.
Here is my Method, let me know your expert comment.
Uwe Keim28k3232 gold badges140140 silver badges223223 bronze badges
Pritam KarmakarPritam Karmakar1,59333 gold badges2121 silver badges4444 bronze badges
3 Answers
A breadth first search is usually implemented with a queue, a depth first search using a stack.
As an alternative to checking for
null
after dequeuing you can check before adding to the Queue. I didn't compile the code, so it might contain some small mistakes.A fancier (but slower) version that integrates well with LINQ:
Which can be used together with a
Children
property on Node
:...
CodesInChaosCodesInChaos91.1k1414 gold badges176176 silver badges232232 bronze badges
Viacheslav SmityukhViacheslav Smityukh4,32911 gold badge1717 silver badges3333 bronze badges
using DFS approach: The tree traversal is O(n)
The method that does traversal:
SaravananSaravanan