#include<stdio.h>
#include<conio.h>
typedef struct node node;
struct node
{
int info;
node *left;
node *right;
};
node *root=NULL;
void inorder(node *n)
{
if(n->left!=NULL) inorder(n->left);
printf("%d",n->info);
if(n->right!=NULL) inorder(n->right);
}
void postorder(node *n)
{
if(n->left!=NULL) inorder(n->left);
if(n->right!=NULL) inorder(n->right);
printf("%d",n->info);
}
void preorder(node *n)
{
printf("%d",n->info);
if(n->left!=NULL) inorder(n->left);
if(n->right!=NULL) inorder(n->right);
}
main()
{
FILE *f=fopen("hinput.txt","r");
char c[5];
node *ptr;
while(fscanf(f,"%s",c)!=EOF)
{
ptr=(node*)malloc(sizeof(node));
ptr->info=atoi(c);
if(root==NULL)
{
root=ptr;
root->left=NULL;
root->right=NULL;
}
else
{
node *temp=root;
while(1)
{
if(temp->info>=ptr->info)
{
if(temp->left==NULL)
{
temp->left=ptr;
ptr->left=NULL;
ptr->right=NULL;
break;
}
else temp=temp->left;
}
else
{
if(temp->right==NULL)
{
temp->right=ptr;
ptr->left=NULL;
ptr->right=NULL;
break;
}
else temp=temp->right;
}
}
}
}
printf("Preorder Traversal :"); preorder(root);
printf("\nInorder Traversal :"); inorder(root);
printf("\npostorder Traversal :"); postorder(root);
fclose(f);
getch();
}
#include<conio.h>
typedef struct node node;
struct node
{
int info;
node *left;
node *right;
};
node *root=NULL;
void inorder(node *n)
{
if(n->left!=NULL) inorder(n->left);
printf("%d",n->info);
if(n->right!=NULL) inorder(n->right);
}
void postorder(node *n)
{
if(n->left!=NULL) inorder(n->left);
if(n->right!=NULL) inorder(n->right);
printf("%d",n->info);
}
void preorder(node *n)
{
printf("%d",n->info);
if(n->left!=NULL) inorder(n->left);
if(n->right!=NULL) inorder(n->right);
}
main()
{
FILE *f=fopen("hinput.txt","r");
char c[5];
node *ptr;
while(fscanf(f,"%s",c)!=EOF)
{
ptr=(node*)malloc(sizeof(node));
ptr->info=atoi(c);
if(root==NULL)
{
root=ptr;
root->left=NULL;
root->right=NULL;
}
else
{
node *temp=root;
while(1)
{
if(temp->info>=ptr->info)
{
if(temp->left==NULL)
{
temp->left=ptr;
ptr->left=NULL;
ptr->right=NULL;
break;
}
else temp=temp->left;
}
else
{
if(temp->right==NULL)
{
temp->right=ptr;
ptr->left=NULL;
ptr->right=NULL;
break;
}
else temp=temp->right;
}
}
}
}
printf("Preorder Traversal :"); preorder(root);
printf("\nInorder Traversal :"); inorder(root);
printf("\npostorder Traversal :"); postorder(root);
fclose(f);
getch();
}
No comments:
Post a Comment
Have some problem with this code? or Request the code you want if you cant find it in Blog Archive.