Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BFS in binary tree

I'm trying to write the codes for breadth-first search in binary tree. I've stored all the data in a queue, but I can't figure out how to travel to all nodes and consume all their children.

Here's my code in C:

void breadthFirstSearch (btree *bt, queue **q) {
   if (bt != NULL) {

      //store the data to queue if there is

      if (bt->left != NULL) enqueue (q, bt->left->data);
      if (bt->right != NULL) enqueue (q, bt->right->data);

      //recursive

      if (bt->left != NULL) breadthFirstSearch (bt->left, q);
      if (bt->right != NULL) breadthFirstSearch (bt->right, q);
   }
}

I've already enqueued the root data, but it's still not working. Can anyone point out my mistake?

like image 917
jason Avatar asked May 17 '11 02:05

jason


People also ask

Is a BFS tree a binary tree?

The Tree constructed by Breadth First Search is not necessarily a Binary Tree. According to Wikipedia,a binary tree is a tree data structure in which each node has at most two child nodes. The node(s) of a tree constructed by BFS may contain any number of Child nodes .

What is BFS and DFS?

BFS(Breadth First Search) uses Queue data structure for finding the shortest path. DFS(Depth First Search) uses Stack data structure. 3. Definition. BFS is a traversal approach in which we first walk through all nodes on the same level before moving on to the next level.

What is BFS algorithm example?

Example BFS AlgorithmYou have a graph of seven numbers ranging from 0 – 6. 0 or zero has been marked as a root node. 0 is visited, marked, and inserted into the queue data structure. Remaining 0 adjacent and unvisited nodes are visited, marked, and inserted into the queue.


2 Answers

A BFS can be easily written without recursion. Just use a queue to order your expansions:

void BFS(btree *start)
{
    std::deque<btree *> q;
    q.push_back(start);
    while (q.size() != 0)
    {
        btree *next = q.front();
        // you may want to print the current node here or do other processing
        q.pop_front();
        if (next->left)
            q.push_back(next->left);
        if (next->right)
            q.push_back(next->right);
    }
}

The key is that you don't need to traverse the tree recursively; you just let your data structure handle the order in which you visit nodes.

Note that I'm using the C++ deque here, but anything that lets you put items on the back and get them from the front will work fine.

like image 113
Nathan S. Avatar answered Sep 29 '22 01:09

Nathan S.


void bfs_bintree (btree_t *head)
{
  queue_t *q;
  btree_t *temp;

  q = queue_allocate ();
  queue_insert (q, head);

  while (!queue_is_empty (q))
  {
    temp = queue_remove (q);

    if (temp->left)
      queue_insert (temp->left);

    if (temp->right)
      queue_insert (temp->right);
  }
  queue_free (q);
  return;
}

First the head node is inserted into the queue. The loop will iterate while the queue is not empty. Starting from the head node, in each iteration one node is removed and the non-null childs are inserted in the queue. In each iteration one node gets out and its non-null childs gets pushed. In the next iteration the next oldest discovered vertex, which is now at the front of the queue , is taken out (in the order they were discovered) and then they are processed to check their child.

                                A
                               / \
                              /   \
                             B     C
                            / \     \
                           /   \     \
                          D     E     F
                         / \         / \
                        /   \       /   \
                       G     H     I     J


iteration  Vertex Selection Discovery Queue State
 initial                    :  A
    1            A          :  B C     {A is removed and its children inserted}
    2            B          :  C D E   {B is removed and its only child inserted}
    3            C          :  D E F   {C is removed and its children inserted}
    4            D          :  E F G H {D is removed and its children inserted}
    5            E          :  F G H   {E is removed and has not children}
    6            F          :  G H I J {F is removed and its children inserted}
    7            G          :  H I J   {G is removed has no children}
    8            H          :  I J     {H is removed has no children}
    9            I          :  J       {I is removed has no children}
    10           J          :  (empty) {J is removed has no children}

Above the iteration stops when we get that there is no more discovered vertex which are waiting to be selected, in the queue, so all the vertices which were discovered in the binary tree (graph connected component) is selected.

I your code first you pass enqueue the nodes in queue and then traverse these childs again recursively, which creates a DFS pattern. If you have to do recursion, you need to check for if the queue is empty as the base condition. Also have a check how you are passing the queue, i think it may be incorrect. I would suggest an iterative solution.

like image 24
phoxis Avatar answered Sep 29 '22 01:09

phoxis