Binary tree using C... & Tree traversals

shital3144 0 Tallied Votes 185 Views Share

It includes Binay tree construction,Inorder,preorder,postorder traversals

#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<alloc.h>


typedef struct tree
{
 int data;
 struct tree *left,*right,*temp;
 }tree;
 void insert(tree *root);
 void in(tree *root);
	void pre(tree *root);
  void main()
  {
    tree *root;
    clrscr();
    root=(tree *)malloc(sizeof(tree));
    if(root==NULL)
    {
     printf("\n Unable to allocate memory:-");
    }
    printf("\nEnter root data:-");
    scanf("%d",&root->data);
    root->left=NULL;
    root->right=NULL;

    insert(root);
     printf("\n inorder is:-\n");

     in(root);
      printf("\n preorder is:-\n");
     pre(root);
	getch();
    }



     void insert(tree *root)
     {
       char ch;
       tree *child,*temp;
       do
       {
	 child=(tree *)malloc(sizeof(tree));
	 printf("\n enter data:-");
	 scanf("%d",&child->data);
	 child->left=NULL;
	 child->right=NULL;
	 temp=root;
	 while(1)
	 {
	  printf("\n At left or right %d(l/r):-",temp->data);
	  scanf("%s",&ch);
	   if(ch=='l')
	   {
	     if(temp->left==NULL)
	     {
	       temp->left=child;
	       break;
	       }
	       else
		 {
		 temp=temp->left;
		 }
	       }
	  if(ch=='r')
	  {

		if(temp->right==NULL)
	     {
	       temp->right=child;
	       break;
	       }
	       else
		 {
		 temp=temp->right;
		 }
	       }
      }
	 printf("\n do u want to add another:-(y\n)");
	 ch=getch();
       }while(ch=='y');
    }

  void in(tree *root)
  {
    if(root!=NULL)
    {
      in(root->left);
      printf("%d",root->data);
      in(root->right);
   }

 }
	void pre(tree *root)
  {
    if(root!=NULL)
    {
    printf("%d",root->data);
      pre(root->right);
      pre(root->left);
   }

 }
sahasrara 0 Newbie Poster

Hi
tihs portion that you write is wrong :
void pre(tree *root)
{
if(root!=NULL)
{
printf("%d ",root->data);
pre(root->right);
pre(root->left);
}

instead of this ,please write it :
void pre(tree *root)
{
if(root!=NULL)
{
printf("%d ",root->data);
pre(root->left);
pre(root->right);
}

also postorder code has bellow shape:
void post(tree *root)
{
if(root!=NULL)
{
pre(root->left);
pre(root->right);
printf("%d ",root->data);
}

that I know , you knew. isn't it sir?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.