MINMAX of a node from root


// code here:
//function to return min and max value, an element 
//to be inserted can have in a BST:

int mini;
int maxi;
void help(TreeNode* rootint nodeX){
    if(nodeX == root->data || root == NULL){
        return;
    }

    if(nodeX > root->data){
        mini= root->data;
        help(root->right, nodeX);
    }
    else if(nodeX < root->data){
        maxi = root->data;
        help(root->left, nodeX);
    }

    return;

}

pair<int,intminMax(TreeNode* rootint nodeX){
    mini = INT_MIN;
    maxi = INT_MAX;

    help(rootnodeX);

    return {mini, maxi};
}


int main(){
    // makeTree() use number of elements = 1 3 7 15 (2**h - 1)
    // driver code

    TreeNode* root = makeTree({8,5,10,2,6,9,13}, 0);
    printTree_IN(root);
    cout << endl;

    pair<int,int> ans = minMax(root, 2);
    cout << ans.first << " " << ans.second << endl;

    return 0;
}

Comments

Popular Posts