My accepted code (recursive)

  • 3
    class Solution {
        TreeNode *buildTreeTmp(vector<int>::iterator prel, vector<int>::iterator prer, 
        								 vector<int>::iterator inl, vector<int>::iterator inr){
    	if (prel >= prer)
    		return NULL;
    	int val = *prel;
    	TreeNode *root = new TreeNode(val);
    	vector<int>::iterator rootIndex = find(inl, inr, val); 
    	vector<int>::size_type lsize = rootIndex - inl;
    	root->left = buildTreeTmp(prel + 1, prel + 1 + lsize, inl, rootIndex);
    	root->right = buildTreeTmp(prel + 1 + lsize, prer, rootIndex + 1, inr);
        return root;
        TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
            return preorder.size() == 0 ? NULL : buildTreeTmp(preorder.begin(), preorder.end(), inorder.begin(), inorder.end());

    Do not use other tempory variable to save child nodes, or will be "Memory Limit Exceeded"

  • 0

    I meet MLE using the recursive method ,similar to yours ,but I use tempory variables to save the child nodes. why is that ?not even only two variables?

  • 0

    iterator pointer is enough, if you use tempory vector variable to save child nodes, it will be "Memory Limit Exceeded".

  • 0
    This post is deleted!

  • 0

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example

Log in to reply

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