Memory Limit Exceeded


  • 0
    S
    class Solution {
    public:
    	TreeNode *sortedArrayToBST(vector<int> &num) {
    		if (num.empty()) return nullptr;
    		_ptrNum = &num;
    		int iRoot = num.size() / 2;
    		TreeNode* root = new TreeNode(*(num.begin() + iRoot));
    		_attachNode(root, 0, iRoot - 1, iRoot + 1, num.size() - 1);
    		return root;
    	}
    private:
    	void _attachNode(TreeNode* parent, int beginLeft, int endLeft, int beginRight, int endRight) {
    		if (endLeft >= beginLeft) {
    			//calculate position of the root of left subtree
    			int leftPos = (endLeft - beginLeft + 1) / 2;
    			//attach node
    			TreeNode* leftChild = new TreeNode(*(_ptrNum->begin() + leftPos));
    			parent->left = leftChild;
    			//recursively deal with left sub tree
    			if (endLeft > beginLeft) {
    				_attachNode(leftChild, beginLeft, leftPos - 1, leftPos + 1, endLeft);
    			}
    		}
    		if (endRight >= beginRight) {
    			int rightPos = (endRight - beginRight + 1) / 2 + beginRight;
    			TreeNode* rightChild = new TreeNode(*(_ptrNum->begin() + rightPos));
    			parent->right = rightChild;
    			if (endRight > beginRight) {
    				_attachNode(rightChild, beginRight, rightPos - 1, rightPos + 1, endRight);
    			}
    		}
    
    	}
    	vector<int> *_ptrNum;
    };
    

    Got Memory Limit Exceeded Error, but I cannot find the reason.


Log in to reply
 

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