Memory Limit Exceeded

  • 0
    class Solution {
        TreeNode *buildTree(vector<int> &inorder, vector<int> &preorder) {
            if (inorder.size() == 0) return nullptr;
            stack<TreeNode*> s;
            int initer = 0, preiter = 0;
            TreeNode *root = new TreeNode(preorder[preiter++]);
            TreeNode *p = nullptr;
            while (true) {
                // The node on top of the stack has no left sub-tree
                if (>val == inorder[initer]) {
                    p =;
                    if (initer == inorder.size()) break;
                    if (s.size() &&>val == inorder[initer]) continue;
                    p->right = new TreeNode(preorder[preiter++]);
                } else {    
                    p = new TreeNode(preorder[preiter++]);
          >left = p;
            return root;

    I solve this problem by using stack and maintain the root of each subtree iteratively. But the OJ says my program gets Memory Limit Exceeded, no idea why. This algorithm has time and space complexity O(n). Could anyone help me on this?

Log in to reply

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