11BST
11BST
#include <stdio.h> #include <conio.h> #include <alloc.h> struct btreenode { struct btreenode *leftchild ; int data ; struct btreenode *rightchild ; }; void insert ( struct btreenode **, int ) ; void display ( struct btreenode * ) ; void main( ) { struct btreenode *bt ; int req, i = 1, num ; bt = NULL ; /* empty tree */ clrscr( ) ; printf ( "Specify the number of items to be inserted: " ) ; scanf ( "%d", &req ) ; while ( i++ <= req ) { printf ( "Enter the data: " ) ; scanf ( "%d", &num ) ; insert ( &bt, num ) ; } printf ( "\n Tree is as follows : \n" ) ; display ( bt ) ; getche(); } /* inserts a new node in a binary search tree */ void insert ( struct btreenode **sr, int num ) { if ( *sr == NULL ) { *sr = malloc ( sizeof ( struct btreenode ) ) ;
( *sr ) -> leftchild = NULL ; ( *sr ) -> data = num ; ( *sr ) -> rightchild = NULL ; return ; } else /* search the node to which new node will be attached */ { /* if new data is less, traverse to left */ if ( num < ( *sr ) -> data ) insert ( &( ( *sr ) -> leftchild ), num ) ; else /* else traverse to right */ insert ( &( ( *sr ) -> rightchild ), num ) ; } return ; } void display ( struct btreenode *sr ) { if ( sr != NULL ) { /* print the data of a node */ printf ( "\t%d", sr -> data ) ; /* traverse till leftchild is not NULL */ display ( sr -> leftchild ) ; /* traverse till rightchild is not NULL */ display ( sr -> rightchild ) ; } else return ; }
OUTPUT
Specify the number of items to be inserted: 6 Enter the data: 76 Enter the data: 34 Enter the data: 90 Enter the data: 56 Enter the data: 34 Enter the data: 23 76 Tree is as follows: 34 23 56 34 90