home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #30 / NN_1992_30.iso / spool / comp / lang / c / 18708 < prev    next >
Encoding:
Text File  |  1992-12-21  |  1.9 KB  |  101 lines

  1. Newsgroups: comp.lang.c
  2. Path: sparky!uunet!ferkel.ucsb.edu!taco!rock!stanford.edu!agate!spool.mu.edu!uwm.edu!ux1.cso.uiuc.edu!cs.uiuc.edu!sparc0b!ctaylor
  3. From: ctaylor@cs.uiuc.edu (Conrad Taylor)
  4. Subject: What's wrong with the following code...?
  5. Message-ID: <BzKnzo.Gt@cs.uiuc.edu>
  6. Sender: news@cs.uiuc.edu
  7. Organization: University of Illinois at Urbana-Champaign
  8. Date: Sun, 20 Dec 1992 19:11:48 GMT
  9. Lines: 90
  10.  
  11.          Could someone please assist me with the following code which it
  12. to build a binary tree and print out the tree nodes?  Thanks in advance to
  13. all that reply.
  14.  
  15. -Con
  16.  
  17. ps:  My e-mail is ctaylor@silver.lcs.mit.edu or
  18.      taylor1@wse.eecs.uic.edu.
  19.  
  20.  
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23.  
  24. struct node {
  25.    int Info;
  26.    struct node *LeftTree;
  27.    struct node *RightTree;
  28. };
  29.  
  30. typedef struct node *NODEPTR;
  31.  
  32. NODEPTR Root;
  33.  
  34. void    TreeInsert(int Number, NODEPTR Root);
  35. void    TreeBuild(NODEPTR Root);
  36. void    TreePrint(NODEPTR Root);
  37.  
  38.  
  39.  
  40.  
  41. void TreeBuild(NODEPTR Root)
  42. {
  43.     Root = NULL;
  44.  
  45.     TreeInsert(6, Root);
  46.     TreeInsert(4, Root);
  47.     TreeInsert(8, Root);
  48.     TreeInsert(7, Root);
  49.     TreeInsert(9, Root);
  50.     TreeInsert(5, Root);
  51.     TreeInsert(3, Root);
  52. } /* end TreeBuild */
  53.  
  54.  
  55.  
  56.  
  57. void TreeInsert(int Number, NODEPTR Root)
  58. {
  59.     if (Root == NULL)
  60.       {
  61.      Root = (NODEPTR)malloc(sizeof(struct node));
  62.      Root->Info  = Number;
  63.      Root->LeftTree = NULL;
  64.      Root->RightTree = NULL;
  65.       }
  66.     else if (Number < Root->Info)
  67.       TreeInsert(Number, Root->LeftTree);
  68.     else if (Number > Root->Info)
  69.       TreeInsert(Number, Root->RightTree);
  70.     /* else if (Number = Root->Info) */
  71.     /*   do nothing since Number is already in the tree. */
  72. } /* end TreeInsert */
  73.  
  74.  
  75.  
  76.  
  77. void TreePrint(NODEPTR Root)
  78. {
  79.    if (Root != NULL)
  80.      {
  81.     TreePrint(Root->LeftTree);
  82.     printf("%2d\n", Root->Info);
  83.     TreePrint(Root->RightTree);
  84.      }
  85. }
  86.  
  87.  
  88.  
  89.  
  90. int main(void)
  91. {
  92.   printf("Start the program.\n"); 
  93.   TreeBuild(Root);
  94.   TreePrint(Root);
  95.   printf("Finish the program.\n"); 
  96.  
  97.   return 0;
  98. }
  99.  
  100.  
  101.