How to tune memory usage in javascript?

  • 0

    One possible reason may be I put too many sub array in lexical scope of the recursion here.

    If changing the preorder, inorder parameter to index start/end in the only copy, it makes the code dame hard to read/write.

    Update: even I change the sub array to index start/end, still complains... see here:

    var buildTreeFromRootNd = function(node, preorder, inorder) {
      //this means there is no sub tree
      if (preorder.length === 1) {
        node.left = null;
        node.right = null;
      var rootIndexInIn = inorder.indexOf(preorder[0]);
      var rightRootIndexInPre = rootIndexInIn+1;
      var tmp = preorder[1];
      var tmpIndexInInorder = inorder.indexOf(tmp);
       //in preorder the next element after root coud be either left node or right node.
       //if this element is in the right branch in inorder
       //this means it has no left node
      if (tmpIndexInInorder > rootIndexInIn) {
        node.left = null;
      } else {
        var leftVal = tmp;
        node.left = new TreeNode(leftVal);
        var leftPreorder = preorder.slice(1, rightRootIndexInPre);
        var leftInorder = inorder.slice(0, rootIndexInIn);
        buildTreeFromRootNd(node.left, leftPreorder, leftInorder);
      var rightVal = preorder[rightRootIndexInPre];
      if (typeof rightVal === 'undefined') {
        node.right = null;
      } else {
        node.right = new TreeNode(rightVal);
        rightPreorder = preorder.slice(rightRootIndexInPre);
        rightInorder = inorder.slice(rootIndexInIn + 1);
        buildTreeFromRootNd(node.right, rightPreorder, rightInorder);
    var buildTree = function(preorder, inorder) {
        return null;
      var root = new TreeNode(preorder[0]);
      buildTreeFromRootNd(root, preorder, inorder);
      return root;

Log in to reply

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