Monday 8 June 2015

Program for breadth first traversal of a tree in C 

It can be done using many methods
We will be using queue to implement bfs as it consumes space but takes less time due space time trade off





#include<stdio.h>
#include<stdlib.h>
struct node
{
int key;
struct node *left;
struct node *right;
};
void bfs(struct node *r)
{
    int front=0, rear=0;
struct node **queue= (struct node **)malloc(100*sizeof(struct node *));//using array of size 100 to store    the pointers to the node
// the array is the array of pointers and hence pointer to pointer double pointer is used here
//We can also use linked list form of queue but for simplicity we have taken a fixed size 
queue[0]=r;
struct node *temp;
while(queue[front]!=NULL)
{
temp=queue[front];
printf("%d",temp->key);
printf(" ");
if(temp->left)
{
  queue[++rear]=temp->left;
}
if(temp->right)
{
    queue[++rear]=temp->right;
}
front++;
}

}
int main()
{
struct node * root;
root= (struct node *)malloc(sizeof(struct node));
root->key=1;
struct node*temp;
//Lets First Create the tree
temp= (struct node *)malloc(sizeof(struct node));
temp->key=2;
temp->left=NULL;
temp->right=NULL;
root->left=temp;
temp= (struct node *)malloc(sizeof(struct node));
temp->key=3;
temp->left=NULL;
temp->right=NULL;
root->right=temp;
temp= (struct node *)malloc(sizeof(struct node));
temp->key=4;
temp->left=NULL;
temp->right=NULL;
root->left->left=temp;
temp= (struct node *)malloc(sizeof(struct node));
temp->key=5;
temp->left=NULL;
temp->right=NULL;
root->left->right=temp;
bfs(root);

return 0;
}

Output:

No comments:

Post a Comment