Construct bst from preorder

code: https://ide.codingblocks.com/s/584574

problem: https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/

I have put a check for NULL in line 30 but still it is showing an error due to left being NULL.

you just have to do this

TreeNode* build(TreeNode* &root,int val){
        if(root == nullptr){
            //cout<<"Now val "<<val<<endl;
            return new TreeNode(val);;
        }
        //cout<<root->val<<" ";
        if(root->val < val) root->right = build(root->right,val);
        if(root->val > val) root->left = build(root->left,val);
        return root;
    }
    TreeNode* bstFromPreorder(vector<int>& preorder) {
        if(preorder.size()==0) return nullptr;
        TreeNode* root = nullptr;
        for(int i=0;i<preorder.size();i++){
            root = build(root,preorder[i]);
        }
        return root;
    }

what’s the approach you are using.


second method of this blog

both have same time complexity, you can go with the method i have mentioned above.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.