MIN MAX Technique BST from preorder only

// code here:
// construct a BST from preorder only. SC = TC = O(N).
// https://practice.geeksforgeeks.org/problems/preorder-to-postorder4423/1#

// min max technqiue -> right and left values change.
// fitting the current value in range since rLR. 

int idx;
TreeNode* help(int maxint minint pre[], int n){

    if(idx >= nreturn NULL;

    TreeNode* root = NULL;

    int cur = pre[idx];
    if(cur < max and cur > min){
        //make new root, idx update:
        root = new TreeNode(cur);
        idx += 1;
    }

    // make left first and then after completion only make right:
    if(idx < n) root->left = help(root->data, minpren);
    if(idx < n) root->right = help(max, root->data, pren);

    //NOTE: 
    //if both in same "if" then there will be error in idx value.

    return root;

}

TreeNode* preorderBST(int pre[], int n){
    idx = 0;
    return help(INT_MAXINT_MINpren);
}

Comments

Popular Posts