#include <stdio.h>
#include <stdlib.h>
struct tree {
int data ;
struct tree * left ;
struct tree * right ;
} * root = NULL ;
struct tree * createNode ( int val ) {
struct tree * newNode = ( struct tree * ) malloc ( sizeof ( struct tree ) ) ;
newNode -> left = NULL ;
newNode -> right = NULL ;
newNode -> data = val ;
return newNode ;
}
struct tree * insert ( struct tree * node , int val ) {
if ( node == NULL )
return createNode( val ) ;
if ( val < node -> data )
node -> left = insert ( node -> left , val ) ;
else if ( val > node -> data )
node -> right = insert ( node -> right , val ) ;
return node ;
}
void inorder ( struct tree * node )
{
if ( node != NULL )
{
inorder ( node -> left ) ;
printf ( " %d " , node -> data ) ;
inorder ( node -> right ) ;
}
}
void preorder ( struct tree * node )
{
if ( node != NULL )
{
printf ( " %d " , node -> data ) ;
preorder ( node -> left ) ;
preorder ( node -> right ) ;
}
}
void postorder ( struct tree * node )
{
if ( node != NULL )
{
postorder ( node -> left ) ;
postorder ( node -> right ) ;
printf ( " %d " , node -> data ) ;
}
}
void levelorder ( struct tree * node )
{
struct tree * queue [ 500 ] ;
int front , rear ;
queue [ 0 ] = root ;
front = 0 ;
rear = front ;
do {
if ( queue [ front ] -> left )
queue [ ++ rear ] = queue [ front ] -> left ;
if ( queue [ front ] -> right )
queue [ ++ rear ] = queue [ front ] -> right ;
printf ( " %d " , queue [ front ] -> data ) ;
front ++ ;
} while ( front <= rear ) ;
}
int main ()
{
root = insert ( root , 5 ) ;
insert ( root , 3 ) ;
insert ( root , 6 ) ;
insert ( root , 2 ) ;
insert ( root , 1 ) ;
insert ( root , 4 ) ;
printf ( " \n INORDER TRAVERSAL \n " ) ;
inorder ( root ) ;
printf ( " \n PREORDER TRAVERSAL \n " ) ;
preorder ( root ) ;
printf ( " \n POSTORDER TRAVERSAL \n " ) ;
postorder ( root ) ;
printf ( " \n LEVELORDER TRAVERSAL \n " ) ;
levelorder ( root ) ;
return 0 ;
}