Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- struct treeNode{
- struct treeNode *leftPtr;
- int data;
- struct treeNode *rightPtr;
- };
- typedef struct treeNode TreeNode;
- typedef TreeNode *TreeNodePtr;
- void inOrder( TreeNodePtr treePtr )
- {
- // if tree is not empty, then traverse
- if ( treePtr != NULL ) {
- inOrder( treePtr->leftPtr ); //Recursion to the left
- printf( "%3d", treePtr->data ); //print the value
- inOrder( treePtr->rightPtr ); //Recursion to the right
- } // end if
- } // end function inOrder
- void insertNode(TreeNodePtr *root, int value){
- TreeNodePtr newnode,treePtr;
- // if tree is empty
- if ( *root == NULL ) {*root = (TreeNode*)malloc(sizeof(TreeNode));
- // if memory was allocated, then assign data
- if ( *root != NULL ) {
- ( *root )->data = value;
- ( *root )->leftPtr = NULL;
- ( *root )->rightPtr = NULL;
- } // end if
- else {
- printf( "%d not inserted. No memory available.\n", value );
- } // end else
- } // end if
- else { // tree is not empty
- treePtr=*root;
- newnode = (TreeNodePtr)malloc(sizeof(TreeNodePtr));
- newnode->leftPtr = NULL;
- newnode->rightPtr = NULL;
- newnode->data=value;
- while(treePtr!=newnode)
- {
- if(value<=(treePtr)->data)
- {
- if(!treePtr->leftPtr) (treePtr)->leftPtr=newnode;
- treePtr=(treePtr)->leftPtr;
- }
- else
- {
- if(!treePtr->rightPtr) {(treePtr)->rightPtr=newnode; }
- treePtr=(treePtr)->rightPtr;
- }
- }
- }
- }
- void printTree(TreeNodePtr treePtr, int n ){
- int a=n,i;
- if ( treePtr != NULL ){
- printTree( treePtr->rightPtr,a+1 );
- for(i=0;i<n;i++) printf(" ");
- printf( "%3d\n", treePtr->data );
- printTree( treePtr->leftPtr,a+1 );
- }
- }
- int main( int argv ,char *argc[])
- {
- int a,b=0;
- unsigned int i; // counter to loop from 1-10
- int item; // variable to hold random values
- TreeNodePtr rootPtr = NULL; // tree initially empty
- srand( time( NULL ) );
- puts( "The numbers being placed in the tree are:" );
- for ( i = 1; i < argv; i++ ) {
- a=atoi(argc[i]);
- //item = rand() % 15; // insert random values between 0 and 14 in the tree
- //printf( "%3d", a );
- insertNode( &rootPtr, a );
- } // end for
- // traverse the tree preOrder
- printTree( rootPtr,b );
- } // end main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement