Friday, November 15, 2019

BINARY TREE

Implementation of Binary Tree

*************
#include<stdio.h>
typedef struct node
{
int data;
struct node *left;
struct node *right;
} node;

node *create()
{
node *p;
int x;
printf("Enter data(-1 for no data):");
scanf("%d",&x);

if(x==-1)
return NULL;

p=(node*)malloc(sizeof(node));
p->data=x;
printf("Enter left child of %d:\n",x);
p->left=create();
printf("Enter right child of %d:\n",x);
p->right=create();
return p;
}

void preorder(node *t) //address of root node is passed in t
{
if(t!=NULL)
{
printf("\n%d",t->data); //visit the root
preorder(t->left); //preorder traversal on left subtree
preorder(t->right); //preorder traversal om right subtree
}
}
int main()

node *root;
root=create();
printf("\nThe preorder traversal of tree is:\n");
preorder(root);
return 0;
}

Binary Search Tree

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

struct node
{
 int data;
 struct node *left;
 struct node *right;
};


void inorder(struct node *root)
{
 if(root)
 {
  inorder(root->left);
  printf("  %d",root->data);
  inorder(root->right);
 }
}

int main()
{
 int n , i;
 struct node *p , *q , *root;
 printf("Enter the number of nodes to be insert: ");
 scanf("%d",&n);

 printf("\nPlease enter the numbers to be insert: ");

 for(i=0;i<i++)
 {
  p = (struct node*)malloc(sizeof(struct node));
  scanf("%d",&p->data);
  p->left = NULL;
  p->right = NULL;
  if(i == 0)
  {
   root = p; // root always point to the root node
  }
  else
  {
   q = root;   // q is used to traverse the tree
   while(1)
   {
    if(p->data > q->data)
    {
     if(q->right == NULL)
      {
      q->right = p;
      break;
      }
     else
      q = q->right;
    }
    else
    {
     if(q->left == NULL)
      {
      q->left = p;
      break;
      }
     else
      q = q->left;
    }
   }

  }

 }

printf("\nBinary Search Tree nodes in Inorder Traversal: ");
inorder(root);
printf("\n");

return 0;
}


























No comments:

Post a Comment