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 max, int min, int pre[], int n){

    if(idx >= n) return 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, min, pre, n);
    if(idx < n) root->right = help(max, root->data, pre, n);

    //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_MAX, INT_MIN, pre, n);
}

Comments

Popular Posts