#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define SIZE 10
typedef struct mynode
{
int data;
struct mynode* lft;
struct mynode* rt;
}TreeNode;
typedef struct
{
int front,back,count;
TreeNode* data[SIZE];
}Queue;
void addNode(TreeNode** root,int value);
void enque(Queue* q,TreeNode* link);
void deque(Queue* q,TreeNode** link);
void init(Queue* q);
int isEmpty(Queue q);
void breadthFirst(TreeNode* root);
void main()
{
TreeNode* root=NULL;
clrscr();
addNode(&root,10);
addNode(&root,8);
addNode(&root,9);
addNode(&root,7);
addNode(&root,12);
addNode(&root,11);
addNode(&root,13);
breadthFirst(root);
getch();
}
void breadthFirst(TreeNode* root)
{
Queue q;
init(&q);
enque(&q,root);
while(!isEmpty(q))
{
deque(&q,&root);
if(root==NULL)
continue;
printf("%d,",root->data);
enque(&q,root->lft);
enque(&q,root->rt);
}
}
int isEmpty(Queue q)
{
if(q.count<=0)
return(1);
else
return(0);
}
void deque(Queue* q,TreeNode** link)
{
if(q->count<=0)
printf("\nQueue is Empty\n");
else
{
*link=q->data[q->front];
q->front =(q->front + 1) % SIZE;
q->count--;
if(q->count==0)
{
q->front=-1;
q->back=-1;
}
}
}
void enque(Queue* q,TreeNode* link)
{
if(q->count>=SIZE)
printf("\nQueue is full\n");
else
{
q->back =(q->back + 1) % SIZE;
q->count++;
q->data[q->back]=link;
if(q->count==1)
q->front=0;
}
}
void init(Queue* q)
{
q->count=0;
q->front=-1;
q->back=-1;
}
void addNode(TreeNode** root,int value)
{
if((*root)==NULL)
{
*root=(TreeNode*)malloc(sizeof(TreeNode));
(*root)->data=value;
(*root)->lft=NULL;
(*root)->rt=NULL;
}
else
{
if(value<(*root)->data)
addNode(&((*root)->lft),value);
else
addNode(&(*root)->rt,value);
}
}
Think of this as a supplement to the earlier post
the problem is, it only shows the traversing of the given numbers in the program...what if we have to taraverse our own numbers??
ReplyDelete