Page 115 - Programming Microcontrollers in C
P. 115

100    Chapter 2  Advanced C Topics

                          word of the node), it is necessary to either traverse to the node on the
                          left or add a new node on the left if there is none there. The code
                   p->left = addtree(p->left,w);

                          does exactly what is needed in this case. This recursive call to
                          addtree() will descend to the left Tnode if one exists. If one does
                          not exist, the pointer to the left Tnode will be NULL, so addtree()
                          will create a new node for this location. addtree() returns a pointer
                          to the new node, so it will be placed in the left pointer of this node.
                              Had the lexical value of the word been greater than that of the
                          word stored in the node, the addtree() call would work on the
                          pointer to the right child node. Therefore, the function addtree()
                          will start at the root node and traverse down the tree to the right or
                          left child nodes depending on the size of the word relative to the
                          sizes of the words in the tree. If the word is found in the tree, its
                          count is incremented. If control proceeds down the tree, and the word
                          is not found, eventually, a Tnode with a NULL pointer to the direc­
                          tion that the path must move. A that time a new Tnode is created
                          and the word is assigned to that Tnode.
                              When all of the data to be input into the tree are read in, control
                          is passed to the function  treeprint(). The  argument  of
                          treeprint() is a pointer to the root node and treeprint()
                          returns nothing to the calling program. Efficient printing out of the
                          data requires another recursive routine. The function treeprint()
                          shown below shows this routine. treeprint() is called with the
                          root pointer as an argument. The root pointer will not be a NULL, so
                          the code following the if statement will be executed. The first

                   /* treeprint: in-order print of tree p */


                   void treeprint(TNODE *p)
                   {
                       if(p !=NULL)
                       {
                          treeprint(p->left);
                          printf(“%4d%15s\n”,p->count,p->word);
                          treeprint(p->right);
                       }
                   }
   110   111   112   113   114   115   116   117   118   119   120