Binary Tree Creation Code Using C

#include<stdio.h>
#include<stdlib.h>
struct node
{
int key;
struct node *left;
struct node *right;
};
struct node *createNode()
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->left=NULL;
temp->right=NULL;
return temp;
}
struct node *queue[100];
int front=-1,rear=-1;
int isEmptyt()
{
    if(front==-1||front==rear+1)
    {
 return 0;
    }
    else
    {
    return 1;
}
}
void Enqueue(struct node *temp)
{
if(front==-1)
{
front=0;
}
rear=rear+1;
queue[rear]=temp;
}
struct node *Dequeue()
{
int t;
if(front==-1||front==rear+1)
{
 return 0;
}
t=front;
front++;
return queue[t];
}
void Delete()
{
front=-1;
rear=-1;
}
struct node* BinaryTree(struct node *root,int key)
{
     struct node *temp=createNode();
     temp->key=key;
     if(root==NULL)
     {
      root=temp;
      return root;
}
     else
     {
      Enqueue(root);
      while(isEmptyt())
      {
        struct node *d=Dequeue();

          if(d->left!=NULL)
 {
    Enqueue(d->left);
 }
 else
 {
    d->left=temp;
Delete();
return root;
 }

          if(d->right!=NULL)
 {
    Enqueue(d->right);
 }
 else
 {
    d->right=temp;
Delete();
return root;
 }
}
}
}

void preorder_rec(struct node *temp)
{
if(temp==NULL)
{
    return;
}
  printf("%d ",temp->key);
  preorder_rec(temp->left);
  preorder_rec(temp->right);
}
struct node *stack[100];
static int top=-1;
void push(struct node *temp)
{
top=top+1;
stack[top]=temp;
}
struct node *pop()
{
  int t;
  t=top;
  top=top-1;
  return stack[t];
}
int isStack()
{
if(top==-1)
{
return 1;
}
else
{
return 0;
}
}
/* PRE-OREDER TREE TRAVERSAL WITHOUT RECURSION*/
void preorder_norec(struct node *temp)
{
    if(temp==NULL)
    {
   printf("\n no element \n");
   return;
}
    while(1)
{
  while(temp)
  {
    printf("%d ",temp->key);
push(temp);
temp=temp->left;
  }
  if(isStack())
  {
  break;
  }
  temp=pop();
  temp=temp->right;
    }
}
int main()
{
  struct node *root=NULL;
  int t,n,v,i;
  while(1)
  {
    printf("\n 1. for insert element \n 2. for preorder recursive \n 3. for preorder non-recursive \n 0 for exit \n");
    scanf("%d",&t);
     switch(t)
     {
      case 1:
      printf("\n how many node you want to enter \n");
scanf("%d",&n);
 for(i=0;i<n;i++)
 {
   printf("\n enter key \n");
   scanf("%d",&v);
  root=BinaryTree(root,v);
 }
break;
   case 2:
    printf("\n pre recursive Tree traversal \n");
    preorder_rec(root);
break;
   case 3:
    printf("\n pre non-recursive Tree traversal \n");
    preorder_norec(root);
break;
case 0:
     exit(0);
}
  }
}

Comments

Popular posts from this blog

BYTE STUFFING PROGRAM USING C

Rotate a matrix 270 degree AntiClockWise

Finding the length of connected cells of 1's (regions) in an matrix of 1's and 0's