Software & Finance





C++ - Binary Search Tree - Minimum and Maximum Node Value





 

Here is the C++ code for identifying the Minimum and Maximum Node Value of a binary search tree node.

 

All the nodes to left are less than the current node value and all nodes to the right are greater than the current node value. It would be true for each and every node in the binary search tree. Click here for validating binary search tree.

 

typedef struct _BSTNode

{

    struct _BSTNode *left;

    struct _BSTNode *right;

    int data;

} BSTNode;

 

static BSTNode *root = NULL;

 

int maxValueOfBST(BSTNode *node, int max = INT_MIN)

{

    if(node == NULL)

        return max;

 

    if(node->data > max)

        max = node->data;

    max = maxValueOfBST(node->left, max);

    max = maxValueOfBST(node->right, max);

    return max;

}

 

int minValueOfBST(BSTNode *node, int min = INT_MAX)

{

    if(node == NULL)

        return min;

 

    if(node->data > min)

        min = node->data;

    min = minValueOfBST(node->left, min);

    min = minValueOfBST(node->right, min);

    return min;

}