depth.c (1608B)
1 /* Exercise 12.19 */ 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 6 struct tree { 7 struct tree *left; 8 int data; 9 struct tree *right; 10 }; 11 typedef struct tree Node; 12 13 void insnode(Node **nodep, int value); 14 int depth(Node *nodep); 15 void showtree(Node *nodep); 16 17 int main(void) 18 { 19 Node *root = NULL; 20 int i; 21 22 for(i = 0; i < 20; i++) { 23 insnode(&root, i); 24 } 25 26 printf("The tree have %d levels which are:\n", depth(root)); 27 showtree(root); 28 29 putchar('\n'); 30 31 return 0; 32 } /* E0F main */ 33 34 /* 35 * Insert an ordered value in the tree 36 */ 37 void insnode(Node **nodep, int value) 38 { 39 if( *nodep == NULL ) { 40 41 if( (*nodep = malloc( sizeof(Node) )) == NULL ) { 42 printf("Cannot allocate the memory"); 43 return; 44 } 45 46 ( *nodep )->data = value; 47 ( *nodep )->left = NULL; 48 ( *nodep )->right = NULL; 49 } 50 else { 51 52 if( value <= ( *nodep )->data ) { 53 insnode( &( ( *nodep )->left ), value ); 54 } 55 else if( value > ( *nodep )->data ) { 56 insnode( &( ( *nodep )->right ), value ); 57 } 58 } 59 60 } /* eof insnode() */ 61 62 /* 63 * Returns the number of tree levels 64 */ 65 int depth(Node *nodep) 66 { 67 Node *currentPtr = nodep; 68 static int count = 0; 69 70 if( nodep != NULL ) { 71 ++count; 72 depth(currentPtr->left); 73 depth(currentPtr->right); 74 } 75 76 return count; 77 78 } /* eof depth() */ 79 80 /* 81 * Show the whole tree 82 */ 83 void showtree(Node *nodep) 84 { 85 Node *currentPtr = nodep; 86 87 if( nodep != NULL ) { 88 printf("%d ", currentPtr->data); 89 showtree(currentPtr->left); 90 showtree(currentPtr->right); 91 } 92 93 } /* eof showtree() */ 94