Skip to main content

BFS of binary tree

Question : Write a function for BFS traversal of a binary tree.


Bread first traversal (also called level order traversal) is a traversal method where you visit the siblings of a node before you visit its descendants.

The other method of traversal is called depth first traversal(DFS) where you visit the descendants of a node before you visit its siblings. In-order, pre-order and post-order are all DFS traversal methods.

In BFS, first you visit all the nodes at level 0, then you visit all the nodes at level 1, then you visit nodes at level 2 etc.
For the diagram shown above, the BFS output should be
8
3 10
1 6 14 
4 7 13  ( there is no newline between levels)

To write a code for BFS, we need to take the help of another data structure - a queue.

  • To start with we insert this root to the queue.
  • Then as long as queue is not empty, we remove a node from the queue,
  • visit this node (display its value)
  • and enqueue its both child nodes. 
Here is C function for BFS


void bfs_traverse(NODEPTR root)
{
    struct queue q1;
    NODEPTR nd;
    q1.front=0;q1.rear =-1;
    enqueue(&q1,root);
    while(!is_empty(q1))
    {
        nd = dequeue(&q1) ;
        printf("%d  ",nd->value);     
        if (nd->left != NULL)
            enqueue(&q1,nd->left);
        if (nd->right != NULL )
            enqueue(&q1,nd->right);         
    }  
}

Here is complete program to display the nodes of a binary search tree in Bread first traversal. You can download this program from here.


#include<stdio.h>
#include<stdlib.h>
struct btnode
{ 
    int value; 
    struct btnode *left, *right; 
};
typedef struct btnode *NODEPTR ;
#define MAX 40
struct queue
{ 
   NODEPTR nodes[40];
   int rear,front;
}; 

 NODEPTR insert_node(NODEPTR nd,NODEPTR newnode)
{
    if(nd==NULL)
       return newnode;/* newnode becomes root of tree*/
    if(newnode->value > nd->value)
        nd->right = insert_node(nd->right,newnode);
    else if(newnode->value <  nd->value)
        nd->left = insert_node(nd->left,newnode); 
    return nd;   
}
 
NODEPTR create_node(int num)
{
     NODEPTR temp = (NODEPTR)malloc(sizeof(struct btnode));
     temp->value = num;
     temp->left = NULL;
     temp->right = NULL;
     return temp;
} 
void enqueue(struct queue *qptr,NODEPTR newnode)
{
    if(qptr->rear>=MAX)
      {
 printf("Queue overflow");
        return;
      }
    qptr->rear++;
    qptr->nodes[qptr->rear]=newnode;
}
int is_empty(struct queue qptr)
{
    if (qptr.front>qptr.rear)
      return 1;
    return 0;
}
  
NODEPTR dequeue(struct queue *qptr)
{
    if(is_empty(*qptr))
    {
 printf("Queue empty");
        return NULL;
    }    
    NODEPTR temp= qptr->nodes[qptr->front];
    qptr->front++;
    return temp;
}
   
/* displaying elements using BFS traversal */

void bfs_traverse(NODEPTR root)
{
    struct queue q1;
    NODEPTR nd;
    q1.front=0;q1.rear =-1;
    enqueue(&q1,root);
    while(!is_empty(q1))
    {
        nd = dequeue(&q1) ;
        printf("%d  ",nd->value);     
        if (nd->left != NULL)
            enqueue(&q1,nd->left);
        if (nd->right != NULL )
            enqueue(&q1,nd->right);         
    }  
}

int main() 
{ 
    NODEPTR root = NULL,newnode ; 
    int num = 1; 
    printf("Enter the elements of the tree(enter -1 to exit)\n"); 

    while (1) 
    {     
        scanf("%d",  &num); 
        if (num  ==  -1) 
            break; 
        newnode = create_node(num);
        root = insert_node(root,newnode);
    }
    printf("elements in bfs are\n"); 
    bfs_traverse(root);
    
}

Comments

Popular posts from this blog

Delete a node from doubly linked list

Deletion operation in DLL is simpler when compared to SLL. Because we don't have to go in search of previous node of to-be-deleted node.  Here is how you delete a node Link previous node of node of to-be-deleted to next node. Link next node of node of to-be-deleted to previous node. Free the memory of node of to-be-deleted Simple, isn't it. The code can go like this. prevnode = delnode->prev; nextnode = delnode->next; prevnode->next = nextnode; nextnode->prev = prevnode; free(delnode); And that is it. The node delnode is deleted. But we should always consider boundary conditions. What happens if we are trying to delete the first node or last node? If first node is to be deleted, its previous node is NULL. Hence step 3 should not be used.  And also, once head is deleted, nextnode becomes head . Similarly if last node is to be deleted, nextnode is NULL. Hence step 4 is as strict NO NO. And we should set prevnode to tail. After we put these things together, we have...

Function to sort an array using bubble sort

Quick and dirty way of sorting an array is bubble sort. It is very easy to write and follow. But please keep in mind that it is not at all effecient. #include<iostream> using std::cin; using std::cout; void readArray(int arr[],int sz); void printArray(int arr[],int sz); void sortArray(int arr[],int sz); void swap(int &a,int &b); int main() {    int sz;    cout<<"Size of the array=";    cin>>sz;    int arr[sz];    readArray(arr,sz);     sortArray(arr,sz);   cout<<"Sorted array is ";   printArray(arr,sz); } void readArray(int arr[],int sz) {  for(int i=0;i<sz;i++)    {       cout<<"arr["<<i<<"]=";       cin>>arr[i];   } } void printArray(int arr[],int sz) {  for(int i=0;i<sz;i++)    {       cout<<"arr["<<i<<"]=";    ...

Merge two binary search trees

How do you merge two binary search trees? I googled about the solutions. Most solutions told me to convert both trees into linked lists. Merge the lists. Then create a tree from the elements of the list. But why lists? Why can't we store the elements in an array? Because if the data of the tree is larger - not just integer keys, array manipulation becomes difficult. But again, we need not convert both the trees into lists. We can convert one tree into list - a doubly linked list. Then insert the elements of this list into the other tree. I tried this approach. To convert a tree into a sorted doubly linked list Create a doubly linked list. Let the prev and next links of nodes in this list be called left and right respectively. This way we can directly use the binary tree nodes in the list. Use a static variable previousnode  call the function recursively for left child of current node. link current node to the previousnode set next pointer of previousnode to curre...