I get strange output limit exceed, I have not print anything


  • 0
    R
    class Solution {
    public:
        TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) 
        {
            
            TreeNode* root=buildTree1(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1);
            return root;
        }
        TreeNode *buildTree1(vector<int> &preorder, vector<int> &inorder, int prestart,int preend, int instart, int inend)
        {
            if(preend<=preorder.size() -1 &&prestart>=0 && inend<=inorder.size() -1 &&instart>=0 && prestart<=preend && instart<=inend)
            {
                TreeNode* root=new TreeNode(preorder[prestart]);
                int i;
                for(i=instart;i<=inend;i++)
                {
                    if(inorder[i]==preorder[prestart])
                        break;
                }
                root->left=buildTree1(preorder,inorder,prestart+1,prestart+i, instart,instart+i-1);
                root->right=buildTree1(preorder,inorder,prestart+i+1,preend,instart+i+1,inend);
                return root;
            }
            else
                return NULL;
        }
        
        
    };
    

    Why OLE? Is recurve solution cost too much stack, so it should be memory limit exceeded....I think, I think
    recursive is the simplest one solution


  • 0
    S

    It could because of the returned tree has tons of nodes, which obviously is wrong answer.


  • 0
    R

    I am not sure what you mean, but I have found the error, that is the recursive parameter, I do not think carefully, i is the index of inorder, so preorder should compute with the rule that inorder and preorder recursive part has the same 'int' numbers


Log in to reply
 

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