Skip to content

Instantly share code, notes, and snippets.

@prasadwrites
Last active August 29, 2015 14:05
Show Gist options
  • Save prasadwrites/cd0ccd9ec62a3b73cab7 to your computer and use it in GitHub Desktop.
Save prasadwrites/cd0ccd9ec62a3b73cab7 to your computer and use it in GitHub Desktop.
BT_traverse
#include <stdio.h>
#include <stdlib.h>
struct node {
struct node *left;
int data ;
struct node *right;
};
struct node *root = NULL;
void insertNode(struct node *q, int data)
{
if (q == NULL)
{
struct node *temp = (struct node *) malloc (sizeof(struct node));
if (temp == NULL)
{
printf("insertNode (%s:%d): malloc failed\n",__FILE__,__LINE__);
return;
}
temp->data = data;
temp->left = NULL;
temp->right = NULL;
root = temp;
printf("insertNode (%s:%d): First Node\n",__FILE__,__LINE__);
return;
}
else if (q->data == data )
{
printf("insertNode (%s:%d): Duplicate entry\n",__FILE__,__LINE__);
return;
}
else if (data < q->data && q->left != NULL )
{
q = q->left;
insertNode(q, data);
}
else if (data > q->data && q->right != NULL)
{
q = q->right;
insertNode(q, data);
}
else if (data < q->data && q->left == NULL )
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
if (temp == NULL)
{
printf("insertNode (%s:%d): malloc failed\n",__FILE__,__LINE__);
return;
}
temp->data = data;
temp->left = NULL;
temp->right = NULL;
q->left = temp;
return;
}
else if (data > q->data && q->right == NULL )
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
if (temp == NULL)
{
printf("insertNode (%s:%d): malloc failed\n",__FILE__,__LINE__);
return;
}
temp->data = data;
temp->left = NULL;
temp->right = NULL;
q->right = temp;
return;
}
}
void inOrderTraversal(struct node *root)
{
if(root != NULL)
{
inOrderTraversal(root->left);
printf("%d\n",root->data);
inOrderTraversal(root->right);
}
}
void preOrderTraversal(struct node *root)
{
if(root != NULL)
{
printf("%d\n",root->data);
preOrderTraversal(root->left);
preOrderTraversal(root->right);
}
}
void postOrderTraversal(struct node *root)
{
if(root != NULL)
{
postOrderTraversal(root->left);
postOrderTraversal(root->right);
printf("%d\n",root->data);
}
}
void main() {
int n,x;
int num_nodes = 7;
for(x=0;x<num_nodes;x++) {
insertNode(root,x);
}
printf("\nInorder Traversal is:\n");
inOrderTraversal(root);
printf("\nPreorder Traversal is:\n");
preOrderTraversal(root);
printf("\nPostorder Traversal is:\n");
postOrderTraversal(root);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment