home *** CD-ROM | disk | FTP | other *** search
/ C Programming Starter Kit 2.0 / SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso / tybc4 / advfun7.cpp < prev    next >
C/C++ Source or Header  |  1993-05-15  |  1KB  |  58 lines

  1. // C++ program which passes parameter to dynamic data
  2.  
  3. #include <iostream.h>             
  4. #include <string.h>
  5.  
  6. const unsigned MAX = 30;
  7.  
  8. typedef struct node* nodeptr;
  9.  
  10. struct node {
  11.    char value[MAX+1];
  12.    nodeptr left;
  13.    nodeptr right;
  14. };
  15.  
  16. void insert(nodeptr& root, const char* item)
  17. // Recursively insert element in binary tree
  18. {
  19.   if (!root)  {
  20.     root = new node;
  21.     strncpy(root->value, item, MAX);
  22.     root->left = NULL;
  23.     root->right = NULL;
  24.   }
  25.   else {
  26.     if (strcmp(item, root->value) < 0)
  27.       insert(root->left,item);
  28.     else
  29.       insert(root->right,item);
  30.   }
  31. }
  32.   
  33. void showTree(nodeptr& root)
  34. {
  35.   if (!root)
  36.     return;
  37.   
  38.   showTree(root->left);
  39.   cout << root->value << "\n";
  40.   showTree(root->right);
  41. }                       
  42.  
  43. main()
  44. {
  45.   char *names[] = { "Virginia", "California", "Maine", "Michigan",
  46.                     "New york", "Florida", "Ohio", "Illinois",
  47.                     "Alaska", "Arizona", "Oregon", "Vermont",
  48.                     "Maryland", "Delaware", "NULL" };
  49.   nodeptr treeRoot = NULL;
  50.   int i = 0;
  51.   
  52.   // insert the names in the binary tree
  53.   while (strcmp(names[i], "NULL") != 0) 
  54.     insert(treeRoot, names[i++]);   
  55.     
  56.   showTree(treeRoot);
  57.   return 0;
  58. }