Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breadth-first traversal

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

private object data; private BinaryNode left; private BinaryNode right; 

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.

public List<LinkedList<BNode>> FindLevelLinkList(BNode root)     {         Queue<BNode> q = new Queue<BNode>();         // List of all nodes starting from root.         List<BNode> list = new List<BNode>();         q.Enqueue(root);         while (q.Count > 0)         {             BNode current = q.Dequeue();             if (current == null)                 continue;             q.Enqueue(current.Left);             q.Enqueue(current.Right);             list.Add(current);         }          // Add tree nodes of same depth into individual LinkedList. Then add all LinkedList into a List         LinkedList<BNode> LL = new LinkedList<BNode>();         List<LinkedList<BNode>> result = new List<LinkedList<BNode>>();         LL.AddLast(root);         int currentDepth = 0;         foreach (BNode node in list)         {            if (node != root)             {                 if (node.Depth == currentDepth)                 {                     LL.AddLast(node);                 }                 else                 {                     result.Add(LL);                     LL = new LinkedList<BNode>();                     LL.AddLast(node);                     currentDepth++;                 }             }         }          // Add the last linkedlist         result.Add(LL);         return result;     } 
like image 690
Pritam Karmakar Avatar asked Feb 24 '11 23:02

Pritam Karmakar


People also ask

What is breadth first traversal?

What is Breadth First Search? Breadth First Search is a traversal technique in which we traverse all the nodes of the graph in a breadth-wise motion. In BFS, we traverse one level at a time and then jump to the next level. In a graph, the traversal can start from any node and cover all the nodes level-wise.

What is breadth traversal?

Breadth-first search is a graph traversal algorithm that starts traversing the graph from the root node and explores all the neighboring nodes. Then, it selects the nearest node and explores all the unexplored nodes. While using BFS for traversal, any node in the graph can be considered as the root node.

What traversal is used in Breadth First Search?

Breadth First Search (BFS) BFS is the most commonly used approach. BFS is a traversing algorithm where you should start traversing from a selected node (source or starting node) and traverse the graph layerwise thus exploring the neighbour nodes (nodes which are directly connected to source node).

Why is breadth first traversal?

Breadth-First Traversal (or Search) for a graph is similar to Breadth-First Traversal of a tree (See method 2 of this post). The only catch here is, that, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array.


2 Answers

A breadth first search is usually implemented with a queue, a depth first search using a stack.

Queue<Node> q = new Queue<Node>(); q.Enqueue(root); while(q.Count > 0) {     Node current = q.Dequeue();     if(current == null)         continue;     q.Enqueue(current.Left);     q.Enqueue(current.Right);      DoSomething(current); } 

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:

public static IEnumerable<T> BreadthFirstTopDownTraversal<T>(T root, Func<T, IEnumerable<T>> children) {     var q = new Queue<T>();     q.Enqueue(root);     while (q.Count > 0)     {         T current = q.Dequeue();         yield return current;         foreach (var child in children(current))             q.Enqueue(child);     } } 

Which can be used together with a Children property on Node:

IEnumerable<Node> Children { get { return new []{ Left, Right }.Where(x => x != null); } } 

...

foreach(var node in BreadthFirstTopDownTraversal(root, node => node.Children)) {    ... } 
like image 174
CodesInChaos Avatar answered Oct 01 '22 15:10

CodesInChaos


var queue = new Queue<BinaryNode>(); queue.Enqueue(rootNode);  while(queue.Any()) {   var currentNode = queue.Dequeue();   if(currentNode.data == searchedData)   {     break;   }    if(currentNode.Left != null)     queue.Enqueue(currentNode.Left);    if(currentNode.Right != null)     queue.Enqueue(currentNode.Right); } 
like image 36
Viacheslav Smityukh Avatar answered Oct 01 '22 13:10

Viacheslav Smityukh