Can anybody help me to figure out what is wrong with my code?


  • 0
    N

    class Solution {
    public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {

         if(preorder.size() == 0)
               return NULL;
            int prePos = 0;
            return helper(preorder, inorder, 0, inorder.size(), prePos);
        }
        
        TreeNode* helper(vector<int>& preorder, vector<int>& inorder, int start, int end, int &preind){
            if(start >= end || preind >= preorder.size()){
               preind--;
               return NULL;
            }
    
            TreeNode* root = new TreeNode(preorder[preind]);
            auto f = find(inorder.begin() + start, inorder.begin() + end, root->val);
            int ind = f - inorder.begin();
            root->left = helper(preorder, inorder, 0, ind, ++preind);
            root->right = helper(preorder, inorder, ind + 1, end, ++preind);
            return root;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.