Solution to Sample Midterm Programming Problem

 

Problem: Write a class member function in C++ for a Binary_Search_Tree class that calculates the numeric maximum value of all values stored in the tree (for a tree that stores integers > = 0).  The function should accept the root of the tree as a parameter. 

 

Solution:  Note - Since the problem states it is a binary search tree we are working with, we can simply follow the chain of right child pointers from the root on down.  The value in the node whose right child pointer is null is the maximum integer value, so there is no need to compare data values.

int    Binary_Search_Tree:: find_max (BinarySTreeNode * Nodeptr)

{

        int maxvalue = 0;

        if (Nodeptr)                                         //check to see if the tree is null

        {maxvalue = Nodeptr-->data;            // get data value

           if (Nodeptr --> r_child)                    // if this node has a right child

                findmax(Nodeptr --> r_child);

        }

return maxvalue;                                        // return last value found

}